1、前言
![](https://img.haomeiwen.com/i11345146/931b4b01bc5c15bf.png)
2、思路
这道题有两个思路,暴力和双指针。
暴力:直接去除首位空格,接着使用正则表达式 "\s+" 分割字符串为字符数组,然后倒序拼接起来即可(一般工程这样使用)。
双指针:使用双指针 i、j。先去掉字符串首尾空格,然后让两个指针开始在字符串末尾,i 不断往前进,直到遇到空格,则将字符串收集起来;然后 i 继续前进,遇到非空格说明到字符了,然后将 j 也移动到 i 的位置,一直到 i 到字符串首位。
3、代码
暴力解法:
class Solution {
public String reverseWords(String s) {
if(s == null || s.length() == 0 || s.matches("\\s+")){
return "";
}
String[] str = s.trim().split("\\s+");
StringBuffer res = new StringBuffer();
for(int i = str.length - 1; i >= 0; i--){
res.append(str[i]).append(" ");
}
return res.substring(0, res.length() - 1);
}
}
双指针解法:
class Solution {
public String reverseWords(String s) {
if(s == null || s.length() == 0 || s.matches("\\s+")){
return "";
}
s = s.trim();
StringBuffer res = new StringBuffer();
int i = s.length() - 1, j = i;
while(i >= 0){
while (i >= 0 && s.charAt(i) != ' '){
i--;
}
res.append(s.substring(i + 1, j + 1)).append(" ");
while (i >= 0 && s.charAt(i) == ' '){
i--;
}
j = i;
}
return res.substring(0, res.length() - 1);
}
}
网友评论