Reverse Words in a String
Source
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Clarification
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
Python
class Solution:
def reverseWords(self, s):
if s is None:
return None
last=len(s)-1
result = []
while last>=0:
tmp=[]
while s[last]!=' ':
tmp.append(s[last])
last-=1
if last<0:
break
else:
last-=1
if tmp:
if result:
result.append(' ')
self.reverse(tmp, 0, len(tmp)-1)
result.append(''.join(tmp))
return ''.join(result)
def reverse(self, s, left, right):
while left<right:
tmp = s[left]
s[left] = s[right]
s[right] = tmp
left+=1
right-=1
Java
public class Solution {
public String reverseWords(String s) {
StringBuilder result = new StringBuilder();
int last=s.length()-1;
while(last>=0){
StringBuilder tmp = new StringBuilder();
while(s.charAt(last)!=' '){
tmp.insert(0, s.charAt(last));
last--;
if(last<0) break;
}
last--;
if(tmp.length()>0){
if(result.length()>0){
result.append(" ");
}
result.append(tmp.toString());
}
}
return result.toString();
}
}