https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/
- 双指针法
public String reverseWords(String s) {
s = s.trim();//删除首尾空格
int i=s.length()-1,j=s.length()-1;
StringBuilder sb = new StringBuilder();
while (i>=0){
while (i>=0&&s.charAt(i)!=' ')i--;//搜索首个空格
sb.append(s.substring(i+1,j+1)+" ");
while (i>=0&&s.charAt(i)==' ')i--;
j=i;
}
if(sb.length()!=0){
sb.deleteCharAt(sb.length()-1);//删除最后一个空格
}
return sb.toString();
}
- 库函数
String[] ss = s.trim().split(" ");
StringBuilder sb = new StringBuilder();
for(int i=ss.length-1;i>=0;i--){
if(ss[i].equals(""))continue;
sb.append(ss[i]+' ');
}
return sb.toString().trim();