算法1
用split将字符串分割成字符串数组
然后用StringBuilder将其拼接起来
Java 代码
class Solution {
public String reverseWords(String s) {
if(s==null)
return "";
s = s.trim();
if(s.length()==0)
return s;
String[] strs = s.split(" ");
int len = strs.length;
for(int i = 0; i < len/2;i++){
String tmp = strs[i];
strs[i] = strs[len-i-1];
strs[len-i-1] = tmp;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len-1; i++) {
sb.append(strs[i]).append(" ");
}
sb.append(strs[len-1]);
return sb.toString();
}
}
算法2
- 先反转整个字符串中的每个字符
- 然后在将每个单词反转回来
Java 代码
class Solution {
public String reverseWords(String s) {
if(s==null)
return "";
s = s.trim();
if(s.length()==0)
return s;
char[] arr = s.toCharArray();
int len = arr.length;
reserver(arr,0,len-1);
int start = 0,end = 0;
while (end!=len){
if(arr[end]==' '){
reserver(arr,start,end-1);
start = end+1;
end++;
}else if(end==len-1){
reserver(arr,start,end);
break;
}else {
end++;
}
}
return new String(arr);
}
private void reserver(char[] arr, int start, int end) {
for (int i = 0; i < (end-start)/2+1; i++) {
char tmp = arr[start+i];
arr[start+i] = arr[end-i];
arr[end-i] = tmp;
}
}
}
sb从后往前加就行了,为啥还要翻转一次