给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
class Solution {
public String reverseWords(String s) {
// 除去开头和末尾的空白字符
s = s.trim();
// 正则匹配连续的空白字符作为分隔符分割
List<String> wordList = Arrays.asList(s.split("\\s+"));
Collections.reverse(wordList);
return String.join(" ", wordList);
}
}
解题思路如下:
- 移除多余空格
- 将整个字符串反转
- 将每个单词反转
class Solution {
public String reverseWords(String s) {
StringBuffer sb = removeSpace(s);
reverseString(sb, 0, sb.length() - 1);
reverseEachWord(sb);
return sb.toString();
}
private StringBuffer removeSpace(String s){
int left = 0;
int right = s.length() - 1;
while(s.charAt(left) == ' ') left++;
while(s.charAt(right) == ' ') right--;
StringBuffer sb = new StringBuffer();
while(left <= right){
char c = s.charAt(left);
if(c != ' ' || sb.charAt(sb.length() - 1) != ' '){ // 如果StringBuffer的最后一个元素不为" "
sb.append(c);
}
left++;
}
return sb;
}
private void reverseString(StringBuffer sb, int left, int right){
while(left < right){
char temp = sb.charAt(left);
sb.setCharAt(left, sb.charAt(right)) ;
sb.setCharAt(right, temp);
left++;
right--;
}
}
public void reverseEachWord(StringBuffer sb){
int slowindex = 0;
int fastindex = 0;
while(fastindex < sb.length()){
if(sb.charAt(fastindex) == ' '){
reverseString(sb, slowindex, fastindex - 1);
slowindex = fastindex + 1;
}
fastindex++;
}
reverseString(sb, slowindex, fastindex - 1);
}
}