[leetcode] 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.

https://oj.leetcode.com/problems/reverse-words-in-a-string/

 

思路:用split方法分割后倒序遍历加入结果中即可。

 

/**
 * http://blog.csdn.net/perfect8886/article/details/20833685
 * 
 * */
public class Solution {
    public String reverseWords(String s) {
        String[] a = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = a.length - 1; i >= 0; i--) {
            if (!a[i].equals("")) {
                sb.append(a[i]);
                sb.append(" ");
            }
        }
        if (sb.length() > 1)
            sb.deleteCharAt(sb.length() - 1);

        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(new Solution().reverseWords("the sky is blue"));
    }

}

 

第二遍记录:

注意split方法可能产生“”,需要判断处理下。

 

复习1

手工实现类似split的功能,从后向前遍历解析出word塞到StringBuilder中即可。注意如何判断一个word的开头和结束。

 

public class Solution {
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        int i = s.length()-1;
        int j = s.length();
        for(;i>=0;i--){
            if(s.charAt(i)==' '){
                j = i;
            }else{
                if(i==0 || s.charAt(i-1)==' '){
                    if(sb.length()!=0){
                        sb.append(" ");
                    }
                    sb.append(s.substring(i,j));
                }
            }
        }
        return sb.toString();
    }
}

  

Follow Up:  Reverse Words in a String II 

Question: 

Similar to Question [6. Reverse Words in a String], but with the following constraints:

“The input string does not contain leading or trailing spaces and the words are always separated by a single space.”

Could you do it in-place without allocating extra space? 

 

 

 

 

 

posted @ 2014-07-07 22:25  jdflyfly  阅读(183)  评论(0编辑  收藏  举报