[leetcode]Reverse Words in a String

时间:2014-07-24 09:57:33   收藏:0   阅读:179

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".

click to show clarification.

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 }

[leetcode]Reverse Words in a String,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!