Reverse Words in a String
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.
算法思路:
栈。(当然也可以逆序,就不需要借助栈了)
代码如下:
1 public class Solution { 2 public String reverseWords(String s) { 3 if(s == null || s.trim().length() == 0) return ""; 4 Stack<String> stack = new Stack<String>(); 5 s = s.trim(); 6 int start = 0,i = 0; 7 for(; i < s.length(); i++){ 8 if(s.charAt(i) == ' '){ 9 String word = s.substring(start, i); 10 stack.add(word); 11 while(s.charAt(i) == ' ') i++; 12 start = i; 13 } 14 } 15 stack.add(s.substring(start, i)); 16 StringBuilder sb = new StringBuilder(); 17 while(!stack.isEmpty()){ 18 sb.append(stack.pop()); 19 sb.append(' '); 20 } 21 return sb.toString().trim(); 22 } 23 }
第二遍:
真真是好久没刷了,连trim方法都不会用了,囧,这一次,感觉s.substring()效率太低,试图用sb逐个append,但是想了想,感觉略蛋疼,还是一个一个截吧,这次采取的是StringBuilder中的insert方法,不再需要借助栈了。
代码如下:
1 public class Solution { 2 public String reverseWords(String s) { 3 if(s == null || s.length() == 0) return ""; 4 int start = 0, end = 0; 5 StringBuilder sb = new StringBuilder(); 6 for(int i = 0; i < s.length(); i++){ 7 while(i < s.length() && s.charAt(i) == ' ') i++; 8 start = i; 9 while(i < s.length() && s.charAt(i) != ' ') i++; 10 if(start == i) continue; 11 sb.insert(0," "); 12 sb.insert(0, s.substring(start,i)); 13 } 14 return sb.toString().trim(); 15 } 16 }