题目:给你一个字符串 s,颠倒字符串中 单词 的顺序。
单词是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开
示例 1:
输入: “the sky is blue”
输出: “blue is sky the”
示例 2:
输入: " hello world! "
输出: “world! hello”
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: “a good example”
输出: “example good a”
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
思路:
1.先去掉多余的空格
the sky is blue
2.翻转全部字符串
eulb si yks eht
3.翻转每个单词
blue is the sky
class Solution {
public String reverseWords(String s) {
//1.删除多余空格
StringBuffer sb = removeSpace(s);
//2.反转字符串
reverseString(sb,0,sb.length()-1);
//3.反转单词
reverseEachWord(sb);
return sb.toString();
}
public StringBuffer removeSpace(String s){
int start = 0,end = s.length() -1;
while(start < end && s.charAt(start) == ' ') start++;
while(start < end && s.charAt(end) == ' ') end--;
StringBuffer sb = new StringBuffer();
while(start <= end){
char c = s.charAt(start++);
if(c != ' '){
sb.append(c);
}else if(sb.charAt(sb.length() - 1) != ' '){
sb.append(c);
}
}
return sb;
}
//双指针翻反转字符串
public void reverseString(StringBuffer sb,int start,int end)
{
while (start < end) {
char temp = sb.charAt(start);
sb.setCharAt(start, sb.charAt(end));
sb.setCharAt(end, temp);
start++;
end--;
}
}
//利用上一个翻转字符串 翻转每个单词
public void reverseEachWord(StringBuffer sb){
int start = 0;
int end = 1;
int n = sb.length();
while(start < n){
while(end < n && sb.charAt(end) != ' '){
end++;
}
reverseString(sb,start,end -1);
start = end + 1;
end = start + 1;
}
}
}



