给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
没有找到Sweetiee的一天只能靠自己了~~
class Solution {
private final char blank = ' ';
public String reverseWords(String s) {
boolean isBlack = false;
StringBuilder rs = new StringBuilder();
char[] chars = s.toCharArray();
int lastIndex = -1;
for (int index = chars.length - 1; index >= 0;index--) {
if (lastIndex == -1) {
// 跳过结尾空格
if (chars[index] == blank) {
continue;
} else {
// 第一次初始化最后一个字母下标
lastIndex = index;
}
}
// 当该值为true时保留最后一个空格的位置
if (isBlack) {
if (chars[index] != blank) {
isBlack = false;
rs.append(blank);
lastIndex = index;
}
// 当该值为false 并且找到单词前面的空格时copy所有字母
} else if (chars[index] == blank){
isBlack = true;
this.combination(chars, index + 1, lastIndex,rs);
lastIndex = index;
}
// 最后一个单词
if (index == 0 && chars[index] != blank) {
this.combination(chars, index, lastIndex,rs);
}
}
return rs.toString();
}
private void combination(char[] chars,int index,int lastIndex,StringBuilder sb) {
while (index <= lastIndex) {
char c = chars[index++];
sb.append(c);
}
}
}
执行用时:3 ms
内存消耗:39.7 MB