- 这道题,可以理解为,将字符串颠倒,但是每个单词原来的顺序是什么还是什么,不能改变单词的组合顺序,比如apple,able这个例子,字符串颠倒后为able,apple。整个字符串顺序颠倒了,但是apple和able这两个单词本身,不可以变化。
- 难点在于,每个单词中间的空格个数是不确定的,我们无法直接用split()等方法,直接按照空格为分隔符,将字符串分隔开来。会分隔出很多空字符串。
- 所以我们不以单个单词这样一个字符串作为单位进行反转,而是把整个字符串,转换为字符数组,进行判断
- 首先转换为字符数组: [ , , h, e, l, l, o, , w, o, r, l, d, , ]可以看到这个例子,有很多空字符串
- 然后我们先从左向右找到第一个非空字符[ , , h, e, l, l, o, , w, o, r, l,
d
, , ] - 然后继续向左找到第一个空格[ , , h, e, l, l, o,空格, w, o, r, l,
d
, , ] - 此时我们就找到了第一个单词的左右下标[ , , h, e, l, l, o, ,
w, o, r, l, d
, , ] - 将其插入新的数组中[w, o, r, l, d, , ],这样就完成了第一个单词的反转工作,也就是将最后一个单词放到第一个位置,然后单词不进行变化
- 然后重复上面的步骤,直到所有单词处理完成
class Solution {
public String reverseWords(String s) {
char[] arr = s.toCharArray();
char[] newArr = new char[s.length()+1];
int index = 0;
int i = s.length()-1;
while(i >= 0){
while(i >= 0 && arr[i] == ' ') i--;
int right = i;
while(i >= 0 && arr[i] != ' ') i--;
for(int j = i + 1; j <= right; j++){
newArr[index++] = arr[j];
if(j == right){
newArr[index++] = ' ';
}
}
}
if(index == 0){
return "";
}
return new String(newArr, 0, index-1);
}
}