题目
题解
法一:纯粹为了做出本题,暴力解
没有技巧全是感情
class Solution {public String reverseWords(String s) {//首先去除首尾空格s = s.trim();String[] strs = s.split("\\s+");StringBuilder sb = new StringBuilder();//定义一个公共的字符反转方法for(int i=strs.length-1;i>=0;i--){sb.append(strs[i]).append(" ");}return sb.toString().trim();}
}
法二:推荐解
结合前面的刷题技巧
整体反转加内部单词反转
1、去除前后字符
2、反转整个字符串
3、反转每个单词
class Solution {/**可以借助之前的题目里的反转字符串的方法,char数组+双指针*/public String reverseWords(String s) {char[] chars=s.toCharArray();//第一步,去除掉首尾和中间多余的空格chars = removeExtraSpaces(chars);//第二步,整个字符串反转reverse(chars,0,chars.length-1);//第三部,反转每个单词int start = 0;for(int i=0;i<=chars.length;i++){if(i== chars.length||chars[i]==' '){reverse(chars,start,i-1);start = i+1;}}return String.valueOf(chars);}public char[] removeExtraSpaces(char[] chars){//快慢指针来实现 原地将多余空格删除掉int slow = 0;for(int fast=0;fast<chars.length;fast++){if(chars[fast]!=' '){//在除了第一个单词外的每个单词前手动插入空格if(slow!=0){chars[slow++]=' ';}while(fast<chars.length&&chars[fast]!=' '){chars[slow++]=chars[fast++];}}}//将新的chars返回,[0,slow]char[] newChar = new char[slow];System.arraycopy(chars,0,newChar,0,slow);return newChar;}public void reverse(char[] chars,int low,int high){if(high>=chars.length){System.out.println("length out of index");return ;}while(low<high){char temp = chars[low];chars[low] = chars[high];chars[high] = temp;low++;high--; }}
}