剑指offer(44)翻转单词顺序列
public class Solution {
//全体翻转之后,再把每个单词翻转
public String ReverseSentence(String str) {
if(str == null || str.length() == 0 || str.length() == 1){
return str;
}
char[] chs = str.toCharArray();
reverse(chs, 0, chs.length-1);
int start = -1;
for(int i = 0;i < chs.length;i++){
if(chs[i] == ' '){
int end = i;
reverse(chs, start + 1, end-1);
start = end;
}
}
reverse(chs, start + 1,chs.length-1);//上一个循环是找空格,所以最后一个单词是没有被翻转的需要单独反转
return new String(chs);
}
public void reverse(char[] chs, int start, int end){
char temp;
while(start < end){
temp = chs[end];
chs[end] = chs[start];
chs[start] = temp;
start++;
end--;
}
}
}