LeetCode:151.翻转字符串里的单词
给你一个字符串 s ,请你反转字符串中 单词 的顺序。
单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。
返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。
注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。
示例 1:
输入:s = “the sky is blue”
输出:“blue is sky the”
示例 2:
输入:s = " hello world "
输出:“world hello”
解释:反转后的字符串中不能存在前导空格和尾随空格。
示例 3:
输入:s = “a good example”
输出:“example good a”
解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。
先去除整个字符串中多余的空格,然后在整体反转字符串,这样对应单词的具体位置就正确了,然后在反转对应的单词即可
public String reverseWords(String s) {
// 移出字符串中多余的看空格
StringBuilder sb = removeOtherSpace(s);
// 反转整个字符串
reverseStr(sb, 0, sb.length() - 1);
// 反转字符串里面的单词
int start = 0;
int end = 0;
while(start < sb.length()){
// 寻找需要反转的单词的终止位置
while(end < sb.length() && sb.charAt(end) != ' '){
end ++;
}
// 反转单词
reverseStr(sb, start, end - 1);
start = end + 1;
end = start + 1;
}
return sb.toString();
}
private StringBuilder removeOtherSpace(String s){
int left = 0;
int right = s.length() - 1;
// 移出字符串前面多余的空格
while(s.charAt(left) == ' ') left++;
// 移出字符串后面多余的空格
while(s.charAt(right) == ' ') right--;
StringBuilder sb = new StringBuilder();
// 开始移出中间多余的空格
while(left <= right){
char ch = s.charAt(left);
if(ch != ' ' || sb.charAt(sb.length() - 1) != ' '){
sb.append(ch);
}
left ++;
}
return sb;
}
// 反转左闭右闭的字符串
private void reverseStr(StringBuilder 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--;
}
}