leetcode-151. 翻轉字符串裏的單詞

給定一個字符串,逐個翻轉字符串中的每個單詞。

示例 1:

輸入: "the sky is blue"
輸出: "blue is sky the"

示例 2:

輸入: "  hello world!  "
輸出: "world! hello"
解釋: 輸入字符串可以在前面或者後面包含多餘的空格,但是反轉後的字符不能包括。

示例 3:

輸入: "a good   example"
輸出: "example good a"
解釋: 如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含一個。

說明:

無空格字符構成一個單詞。
輸入字符串可以在前面或者後面包含多餘的空格,但是反轉後的字符不能包括。
如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含一個。

沒有找到Sweetiee的一天只能靠自己了~~

class Solution {
    private final char blank = ' ';
    public String reverseWords(String s) {
        boolean isBlack = false;
        StringBuilder rs = new StringBuilder();
        char[] chars = s.toCharArray();
        int lastIndex = -1;
        for (int index = chars.length - 1; index >= 0;index--) {
            if (lastIndex == -1) {
                // 跳過結尾空格
                if (chars[index] == blank) {
                    continue;
                } else {
                    // 第一次初始化最後一個字母下標
                    lastIndex = index;
                }
            }
            // 當該值爲true時保留最後一個空格的位置
            if (isBlack) {
                if (chars[index] != blank) {
                    isBlack = false;
                    rs.append(blank);
                    lastIndex = index;
                }
                // 當該值爲false 並且找到單詞前面的空格時copy所有字母
            } else if (chars[index] == blank){
                isBlack = true;
                this.combination(chars, index + 1, lastIndex,rs);
                lastIndex = index;
            } 
            // 最後一個單詞
            if (index == 0 && chars[index] != blank) {
                this.combination(chars, index, lastIndex,rs);
            }
        }
        return rs.toString();
    }

    private void combination(char[] chars,int index,int lastIndex,StringBuilder sb) {
        while (index <= lastIndex) {
            char c = chars[index++];
            sb.append(c);
        }
    }
}

執行用時:3 ms

內存消耗:39.7 MB

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章