1 题目理解
输入:一个字符串s
规则:一个单词是一串非空字符组成的。单词之间用空格分隔。
输出:将字符串按照单词反转字符串。多余的空格只保留一个。
Example 1:
Input: s = “the sky is blue”
Output: “blue is sky the”
Example 2:
Input: s = " hello world "
Output: “world hello”
解释:收尾的多余空格要去掉。
Example 3:
Input: s = “a good example”
Output: “example good a”
Explanation: 多余的空格只保留一个
Example 4:
Input: s = " Bob Loves Alice "
Output: “Alice Loves Bob”
2思路
反转单词之前先理解一下反转字符串。给定字符s=“12345”,反转之后是"54321"。
位置 | 0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|---|
字符 | 1 | 2 | 3 | 4 | 5 |
逆转后 | 5 | 4 | 3 | 2 | 1 |
第0位与第4位字符交换,第1位与第3位字符交换…其实就是a[i]与a[n-1-i]位的字符交换。
对于字符串s=“the sky is blue”,我们可以先完整逆转字符串,然后按空格,将单词再次逆转,最后去掉多余的空格。
class Solution {public String reverseWords(String s) {char[] chars = s.toCharArray();reverseString(chars,0,chars.length-1);reverseWords(chars);int newLen = cleanMoreSpace(chars);return new String(chars,0,newLen);}private int cleanMoreSpace(char[] chars){int i=0,j=0;int n = chars.length;while(j<n){while(j<n && chars[j]==' '){j++;}while(j<n && chars[j]!=' '){chars[i++] = chars[j++];}if(j<n){chars[i++] =' ';}}return i>1 && chars[i-1]==' '?i-1:i;}private void reverseWords(char[] chars){int n = chars.length;for(int i=0;i<n;i++){if(chars[i]!=' '){int j = i;while(j<n && chars[j]!=' '){j++;}if(j-i>1){reverseString(chars,i,j-1);}i=j-1;}}}private void reverseString(char[] chars,int s,int e){while(s<e){char tmp = chars[s];chars[s] = chars[e];chars[e] = tmp;s++;e--;}}
}
3思路2
读取到字符串s中的每个单词,将单词逆向拼接到结果集。
class Solution {public String reverseWords(String s) {String result = "";int i=0;int n = s.length();String word ="";while(i<n){if(s.charAt(i)==' '){if(word.length()>0){result = word +(result.length()>0?" ":"")+result;word="";}while(i<n && s.charAt(i)==' '){i++;}if(i==n) break;}word +=s.charAt(i);i++;}if(word.length()>0){result = word +(result.length()>0?" ":"")+result;}return result;}
}