151. 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".
并remove extra spaces

Solution1:按char操作

思路: 整體全部chars reverse + every words reverse
Time Complexity: O(N) Space Complexity: O(N) 算返回的result

Solution2:按word操作,逆序輸出

思路:按word操作,逆序輸出
Time Complexity: O(N) Space Complexity: O(N) 算返回的result

Solution1 Code:

public class Solution {
  
    public String reverseWords(String s) {
        if (s == null) return null;
        
        char[] a = s.toCharArray();
        int n = a.length;
        
        // step 1. reverse the whole string
        reverse(a, 0, n - 1);
        // step 2. reverse each word
        reverseWords(a, n);
        // step 3. clean up spaces
        return cleanSpaces(a, n);
    }
  
    void reverseWords(char[] a, int n) {
        int i = 0, j = 0;
      
        while (i < n) {
            while (i < j || i < n && a[i] == ' ') i++; // skip spaces
            while (j < i || j < n && a[j] != ' ') j++; // skip non spaces
        reverse(a, i, j - 1);                      // reverse the word
        }
  }
  
    // trim leading, trailing and multiple spaces
    String cleanSpaces(char[] a, int n) {
        int i = 0, j = 0;
      
        while (j < n) {
            while (j < n && a[j] == ' ') j++;             // skip spaces
            while (j < n && a[j] != ' ') a[i++] = a[j++]; // keep non spaces
            while (j < n && a[j] == ' ') j++;             // skip spaces
            if (j < n) a[i++] = ' ';                      // keep only one space
        }
  
        return new String(a).substring(0, i);
  }
  
    // reverse a[] from a[i] to a[j]
    private void reverse(char[] a, int i, int j) {
        while (i < j) {
            char t = a[i];
            a[i++] = a[j];
            a[j--] = t;
        }
    }
}

Solution2 Code:

public class Solution2 {
    public String reverseWords(String s) {        
        String[] tmp = s.split("\\s");
        StringBuilder sb = new StringBuilder();

        for(int i = 1; i <= tmp.length; i++){
            if(tmp[tmp.length - i].equals("")){
                continue;
            }

            sb.append(tmp[tmp.length - i]);
            sb.append(" ");
        }

        return sb.toString().trim();
    }
}

or

public class Solution2 {
    public String reverseWords(String s) {
        String[] words = s.trim().split(" +");
        Collections.reverse(Arrays.asList(words));
        return String.join(" ", words);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容