方法一:
public String reverseWords(String s) {
String[] strings=s.trim().split(" ");
StringBuilder sb=new StringBuilder();
for(int i=strings.length-1;i>=0;i--){
if(strings[i]=="") continue;
sb.append(strings[i]+" ");
}
return sb.toString().trim();
}
方法二:双指针
public String reverseWords(String s){
s=s.trim();
int j=s.length()-1;
int i=j;
StringBuilder res=new StringBuilder();
while(i>=0){
while(i>=0&&s.charAt(i)!=' ') i--;
res.append(s.substring(i+1,j+1)+" ");
while(i>=0&&s.charAt(i)==' ') i--;
j=i;
}
return res.toString().trim();
}