Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = “the sky is blue“,
return “blue is sky the“.
Could you do it in-place without allocating extra space?
这道题和Rotate Array(https://blog.jing.do/4727 )是一个解法。
public class Solution {
public void reverseWords(char[] s) {
rev(s,0,s.length-1);
int pos = 0;
for(int i =0;i<s.length-1;i++){
if(s[i] == ' '){
rev(s,pos,i-1);
pos = i+1;
}
}
rev(s,pos,s.length-1);
}
public void rev(char[] s,int start,int end){
while(start<end){
char temp = s[start];
s[start] = s[end];
s[end] = temp;
start ++;
end --;
}
}
}
微信扫一扫
支付宝扫一扫