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 = "
return "
Given s = "
the sky is blue
",return "
blue is sky the
".
Could you do it in-place without allocating extra space?
Solution 1: rotate each word and then rotate the entire Sting.
public class Solution {
public void reverseWords(char[] s) {
int i=0, n=s.length;
while (i<n){
int j=i;
while (j<n && s[j]!=' ') j++;
reverse(s,i,j-1);
i=++j;
}
reverse(s,0,n-1);
}
private void reverse(char[] s, int i, int j) {
while (i<j){
char temp=s[i];
s[i++]=s[j];
s[j--]=temp;
}
}
}
没有评论:
发表评论