[leetCode]151. 翻轉字串裡的單詞
阿新 • • 發佈:2020-10-28
csdn:https://blog.csdn.net/renweiyi1487/article/details/109336278
題目
給定一個字串,逐個翻轉字串中的每個單詞。
說明:
無空格字元構成一個 單詞 。
輸入字串可以在前面或者後面包含多餘的空格,但是反轉後的字元不能包括。
如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含一個。
示例 1: 輸入:"the sky is blue" 輸出:"blue is sky the" 示例 2: 輸入:" hello world! " 輸出:"world! hello" 解釋:輸入字串可以在前面或者後面包含多餘的空格,但是反轉後的字元不能包括。 示例 3: 輸入:"a good example" 輸出:"example good a" 解釋:如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含一個。 示例 4: 輸入:s = " Bob Loves Alice " 輸出:"Alice Loves Bob" 示例 5: 輸入:s = "Alice does not even like bob" 輸出:"bob like even not does Alice" 提示: 1 <= s.length <= 104 s 包含英文大小寫字母、數字和空格 ' ' s 中 至少存在一個 單詞
思路
- 先去除字串當中多餘的空格
- 將整個字串反轉
- 將字串中的單詞反轉
class Solution { public String reverseWords(String s) { char[] chars = s.toCharArray(); chars = removeExtraSpace(chars); reverse(chars, 0, chars.length - 1); int begin = 0, end = 0; while (end < chars.length) { if (chars[end] == ' ') { reverse(chars, begin, end - 1); begin = end + 1; } end++; } reverse(chars, begin, chars.length - 1); return new String(chars); } private char[] removeExtraSpace(char[] chars) { int n = chars.length; int fastIndex = 0, slowIndex = 0; // 跳過字串開頭的空格 while (fastIndex < n && chars[fastIndex] == ' ') { fastIndex++; } // 去除字串中間的空格 while ( fastIndex < n) { if (fastIndex > 0 && chars[fastIndex] == chars[fastIndex - 1] && chars[fastIndex] == ' ') { fastIndex ++; continue; } else { chars[slowIndex++] = chars[fastIndex]; } fastIndex++; } // 去除字串末尾的空格 if (slowIndex - 1 > 0 && chars[slowIndex - 1] == ' ') { return Arrays.copyOf(chars, slowIndex - 1); } else { return Arrays.copyOf(chars, slowIndex); } } private void reverse(char[] chars, int left, int right) { while (left < right) { char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; left++; right--; } } }