Given an input string, reverse the string word by word.
For example,
Given s = "
return "
Given s = "
the sky is blue
",return "
blue is sky the
".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
For C programmers: Try to solve it in-place in O(1) space.
Solution 1:
public class Solution {
public String reverseWords(String s) {
StringBuilder sb=new StringBuilder();
int n=s.length();
int j=n-1;
while (j>=0) {
while (j>=0 && s.charAt(j)==' ') j--;
int i=j;
while (i>=0 && s.charAt(i)!=' ') i--;
if (i<j) {
sb.append(s.substring(i+1,j+1));
sb.append(' ');
}
j=i-1;
}
int l=sb.length();
if (l==0) return "";
return sb.substring(0,l-1);
}
}
没有评论:
发表评论