Reverse Words in a String

https://leetcode.com/problems/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".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

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 import java.util.ArrayList;
 2 import java.util.List;
 3 import java.util.Stack;
 4 
 5 public class Solution {
 6     public static String reverseWords(String s) {
 7     List<String> li=new ArrayList();
 8         int len0=s.length();
 9         int len1=0;
10         String x="";
11         for(int i=0;i<len0;i++){
12             char c=s.charAt(i);
13             if(c!=' ') x+=c;
14             else{
15             if(x.length()!=0){
16                 len1++;
17                 li.add(x);
18             }
19             x="";
20             }
21         }
22         if(x.length()!=0) li.add(x);
23         Stack<String>st=new Stack();
24         for(String str:li){
25             st.add(str);
26         }
27         s="";
28         while(!st.isEmpty()){
29             s+=st.pop();
30             if(st.size()!=0)
31             s+=" ";
32         }
33         return s;
34     }
35     public static void main(String[]args){
36     System.out.println(reverseWords("   a   b "));
37     }
38 }

 

posted @ 2015-05-07 18:29  打小孩  阅读(110)  评论(0编辑  收藏  举报