【LeetCode】151. 翻轉字串裡的單詞(Reverse Words in a String)
阿新 • • 發佈:2018-11-29
題目描述: 給定一個字串,逐個翻轉字串中的每個單詞。
示例:
輸入: "the sky is blue"
輸出: "blue is sky the"
說明:
- 無空格字元構成一個單詞。
- 輸入字串可以在前面或者後面包含多餘的空格,但是反轉後的字元不能包括。
- 如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含一個。
解法一: 使用 Java API
public String reverseWords(String s) {
// 正則式去掉空格
String[] words = s.trim ().split(" +");
// 翻轉
Collections.reverse(Arrays.asList(words));
// 單詞間隔新增空格
return String.join(" ", words);
}
解法二: 不使用 API ,純裸寫
public String reverseWords(String s) {
if (s == null) return null;
char[] c = s.toCharArray();
// 第一步:反轉整個字串
reverse (c, 0, c.length - 1);
// 第二步:反轉每個單詞
reverseWords(c);
// 第三步:清空空格
return cleanSpaces(c);
}
// 反轉所有單詞
public void reverseWords(char[] c){
int i = 0, j = 0;
while (i < c.length){
while (i < j || i < c.length && c[i] == ' ') i++; // 跳過空格
while (j < i || j < c.length && c[j] != ' ') j++; // 跳過非空格
reverse(c, i, j - 1);
}
}
// 去掉頭部、尾部與中間的多餘空格
public String cleanSpaces(char[] c){
int i = 0, j = 0;
while (j < c.length){
while (j < c.length && c[j] == ' ') j++; // 跳過空格
while (j < c.length && c[j] != ' ') c[i++] = c[j++]; // 去掉所有空格
while (j < c.length && c[j] == ' ') j++; // 跳過空格
if (j < c.length) c[i++] = ' '; // 僅保留一個空格
}
return new String(c).substring(0, i);
}
// 從 i 到 j 反轉陣列 c
public void reverse(char[] c, int i, int j){
while(j > i){
char t = c[i];
c[i++] = c[j];
c[j--] = t;
}
}