Leetcode 151.反转字符串中的单词
题目要求
- 给你一个字符串 s ,请你反转字符串中 单词 的顺序。
- 单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。
- 返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。
- 注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。
示例 1:
输入:s = “the sky is blue”
输出:“blue is sky the”
示例2:
输入:s = " hello world "
输出:“world hello”
解释:反转后的字符串中不能存在前导空格和尾随空格。
示例3:
输入:s = “a good example”
输出:“example good a”
解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。
提交
双反转
先利用双指针使用移除元素的方法移除多余的空格
然后将整个字符串进行反转
最后将每个单词单独反转即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| class Solution { public String reverseWords(String s) { char[] chars = s.toCharArray(); chars = removeExtraSpaces(chars); reverse(chars, 0, chars.length - 1); reverseEachWord(chars); return new String(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++]; } } char[] newChars = new char[slow]; System.arraycopy(chars, 0, newChars, 0, slow); return newChars; }
public void reverse(char[] chars, int left, int right) { if (right >= chars.length) { System.out.println("set a wrong right"); return; } while (left < right) { chars[left] ^= chars[right]; chars[right] ^= chars[left]; chars[left] ^= chars[right]; left++; right--; } }
public void reverseEachWord(char[] chars) { int start = 0; for (int end = 0; end <= chars.length; end++) { if (end == chars.length || chars[end] == ' ') { reverse(chars, start, end - 1); start = end + 1; } } } }
|