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.
Subscribe to see which companies asked this question.
public class Solution {
public String reverseWords(String s) {
if(s.length()==0) return s;
String[] words=s.split(" ");
String str="";
LinkedList<String> list=new LinkedList<>();
for(int i=0;i<words.length;i++){
if(words[i].length()>0)list.addFirst(words[i]);
}
for(int i=0;i<list.size()-1;i++){
str=str+list.get(i)+" ";
}
if(list.size()>0){
str=str+list.get(list.size()-1);
}
return str;
}
}