题目描述:Input:“I am a student.” Output:“student. a am I”
题解:
public class Solution {
public String ReverseSentence(String str) {
char[] chars = str.toCharArray();
int i=0, lasti = 0;
while(i<chars.length){
if(chars[i]!=' '){
i++;
}else{
reverseStr(chars, lasti, i-1);
lasti = ++i;
}
}
reverseStr(chars, lasti, i-1);
reverseStr(chars, 0, chars.length-1);
return new String(chars);
}
void reverseStr(char[] str, int l, int h){
while(l < h){
swap(str, l++, h--);
}
}
void swap(char[] str, int i, int j){
char t = str[i];
str[i] = str[j];
str[j] = t;
}
}