按單詞逆序字符串 Reverse Words in a String

問題:app

Given an input string, reverse the string word by word.ui

For example,
Given s = "the sky is blue",
return "blue is sky the".spa

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

Clarification:ip

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

解決:input

① 直接解決,比較複雜,使用StringBuilder類的方法。string

public class Solution { //21ms
   public static String reverseWords(String s) {
        if(s == null || s.length() == 0) return "";
        s = s.trim();
        String[] str = s.split("\\s+");

        if(str.length == 1) return s;
        StringBuilder sb = new StringBuilder();
        for (int i = 0;i < str.length;i ++){
            if(i > 0 && i <= str.length - 1){
                sb.insert(0," ");
                sb.insert(0,str[i]);
            }else{
                sb.insert(0,str[i]);
            }
        }
        return sb.toString();
    }
it

② 同上面同樣,不過從後面向前掃描。io

public class Solution {//8ms
    public String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        s = s.trim();
        String[] str = s.split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = str.length - 1; i >= 0; -- i) {
            if (! str[i].equals("")) {
                sb.append(str[i]).append(" ");
            }
        }
        return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
    }
}class

③ 在discuss中看到的。

public class Solution {     public String reverseWords(String s) {         String[] array = s.split(" ");         StringBuilder sb = new StringBuilder();         for(int i = array.length - 1; i >= 0; i --) {             if(array[i].length() > 0) sb.append(array[i]).append(" ");         }         return sb.toString().trim();     } }

相關文章
相關標籤/搜索