本题难度不大,核心在于对于小细节的处理,字符串的预处理很重要
public class Solution {
public void reverseArray(String[] words) {
int i = 0, n = words.length - 1;
while (n > 2 * i) {
String x = words[i];
words[i] = words[n - i];
words[n - i] = x;
i++;
}
}
public String reverseWords(String s) {
s=s.trim();
s=s.replaceAll("\\s{1,}", " ");
String[] words = s.split(" ");
reverseArray(words);
int iMax=words.length-1;
if(iMax==-1){
return "";
}
StringBuilder sb=new StringBuilder();
for(int i=0;;i++){
sb.append(words[i]);
if(i==iMax){
break;
}
sb.append(" ");
}
//System.out.println(Arrays.toString(words));
return sb.toString();
}
}