本题首先可以用java内置方法实现,具体参考官方答案。
其次,可以使用多个自制方法实现,源字符串为:"the sky is blue ",创建一个方法实现去除多余空格,"the sky is blue";一个方法实现字符串反转,"eulb si yks eht";一个方法实现单词反转,"blue is sky the"。这题我用的第三种方法做的,这种方法没实现。
第三种方法是利用双指针,这里参考评论区答案思想自己完成实现,但是细节上差的太多,最终还是看着答案改对了。
改正后的答案,主要在一些边界条件的判断有错误。
class Solution {
public String reverseWords(String s) {
int left = 0, right = s.length() - 1;
while (s.charAt(left) == ' ') {left++;}
while (s.charAt(right) == ' ') {right--;}
StringBuilder res = new StringBuilder();
while (left<=right){
int index = right;
while (index >= left && s.charAt(index) != ' ') {index--; }
for (int i = index+1; i <= right; i ++) { res.append(s.charAt(i));}
if (index > left) {
res.append(' ');}
while (index>=left && s.charAt(index) == ' ') {index--;}
right = index;
}
return res.toString();
}
}
原做出来的错误答案
class Solution {
public String reverseWords(String s) {
int left = 0, right = s.length() - 1;
while (s.charAt(left) == ' ') {
left++;
}
while (s.charAt(right) == ' ') {
right--;
}
StringBuilder res = new StringBuilder();
int index = right;
while (left<index){
index = right;
while (s.charAt(index) != ' ' && index > 0) {
index--;
}
for (int i = index+1; i <= right; i ++) {
res.append(s.charAt(i));
}
if (index != left) {
res.append(' ');
}
while (s.charAt(index) == ' ') {
index--;
}
right = index;
}
return res.toString();
}
}
优化后的答案,用char代替String速度更快
class Solution {
public String reverseWords(String s) {
char[] charArray = s.toCharArray();
int left = 0;
int right = charArray.length-1;
StringBuilder sb = new StringBuilder();
while(charArray[left]==' ') left++;
while(charArray[right] == ' ') right--;
while(left <= right){
int index = right;
while(index >= left && charArray[index] != ' ' ) index--;
for(int i = index+1 ; i <= right ; i++ ) sb.append( charArray[i] );
if(index > left) sb.append(' ');
while( index >= left && charArray[index]==' ' ) index--;
right = index;
}
return sb.toString();
}
}