186.反转字符串中的单词II
方法:先反转整个字符串再反转单词中的字母
class Solution {
public void reverseWords(char[] s) {
reverseCharacters(s,0,s.length-1);
reverseEachWord(s);
}
//反转单词中的字母
public void reverseEachWord(char[] s){
int length = s.length;
int begin = 0;
for(int i = 0;i<length;i++){
if(s[i] == ' '){
reverseCharacters(s,begin,i - 1);
begin = i+1;
}
}
reverseCharacters(s,begin,length-1);
}
//反转整个字符串
public void reverseCharacters(char[] s, int low ,int high){
while(low < high){
char c1 = s[low],c2 = s[high];
s[low] = c2;
s[high] = c1;
low++;
high--;
}
}
}