Given an input string, reverse the string word by word.
For example,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.
public class Solution {
public String reverseWords(String s) {
int n = s.length();
// String rec = "";
if(n<=0)
return s;
reverse(0,n-1,s);
int p =0,q= 0;
while(q<=n)
{
if(s.charAt(q)==' '||q == n)
{
reverse(p,q-1,s);
p = q+1;
}
q++;
}
return s;
}
private void reverse(int start,int end,String str)
{
while(start<=end)
{
char temp = str.charAt(start);
str.charAt(start) = str.charAt(end);
str.charAt(end) = temp;
start++;
end--;
}
}
}