題目鏈接
題目描述
輸入一個英文句子,翻轉句子中單詞的順序,但單詞內字符的順序不變。爲簡單起見,標點符號和普通字母一樣處理。例如輸入字符串"I am a student. “,則輸出"student. a am I”。
示例 1:
輸入: “the sky is blue”
輸出: “blue is sky the”
示例 2:
輸入: " hello world! "
輸出: “world! hello”
解釋: 輸入字符串可以在前面或者後面包含多餘的空格,但是反轉後的字符不能包括。
示例 3:
輸入: “a good example”
輸出: “example good a”
解釋: 如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含一個。
說明:
無空格字符構成一個單詞。
輸入字符串可以在前面或者後面包含多餘的空格,但是反轉後的字符不能包括。
如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含一個。
方法1
利用內置 split 方法和 reverse 方法。
優點:寫法最簡單
class Solution {
public String reverseWords(String s) {
// 除去字符串中空格
s = s.trim();
// 通過空格分割字符串:s.split("\\s+")
/新建字符串:/Arrays.asList()
List<String> wordList = Arrays.asList(s.split("\\s+"));
//反轉字符串
Collections.reverse(wordList);
//給字符串中單詞間加入空格
return String.join(" ", wordList);
}
}
方法二:先反轉字符串再反轉每個單詞
在不同語言中這個方法的實現是不一樣的,主要的差別是有些語言的字符串不可變(如 Java 和 Python),有些語言的字符串可變(如 C++)。
對於字符串不可變的語言,首先得把字符串轉化成其他可變的數據結構,同時還需要在轉化的過程中去除空格。
代碼
注意:要使用StringBuilder來操縱字符串
class Solution {
public StringBuilder trimSpaces(String s) {
int left = 0, right = s.length() - 1;
// remove leading spaces
while (left <= right && s.charAt(left) == ' ') ++left;
// remove trailing spaces
while (left <= right && s.charAt(right) == ' ') --right;
// reduce multiple spaces to single one
StringBuilder sb = new StringBuilder();
while (left <= right) {
char c = s.charAt(left);
if (c != ' ') sb.append(c);
else if (sb.charAt(sb.length() - 1) != ' ') sb.append(c);
++left;
}
return sb;
}
public void reverse(StringBuilder sb, int left, int right) {
while (left < right) {
char tmp = sb.charAt(left);
sb.setCharAt(left++, sb.charAt(right));
sb.setCharAt(right--, tmp);
}
}
public void reverseEachWord(StringBuilder sb) {
int n = sb.length();
int start = 0, end = 0;
while (start < n) {
// go to the end of the word
while (end < n && sb.charAt(end) != ' ') ++end;
// reverse the word
reverse(sb, start, end - 1);
// move to the next word
start = end + 1;
++end;
}
}
public String reverseWords(String s) {
// converst string to string builder
// and trim spaces at the same time
StringBuilder sb = trimSpaces(s);
// reverse the whole string
reverse(sb, 0, sb.length() - 1);
// reverse each word
reverseEachWord(sb);
return sb.toString();
}
}