From e9a164add1f9c82318597bfbbc10737f700a8298 Mon Sep 17 00:00:00 2001 From: Flow-sandyu <72751523+Flow-sandyu@users.noreply.github.com> Date: Mon, 3 Oct 2022 17:59:23 +0800 Subject: [PATCH] =?UTF-8?q?update=EF=BC=9A0151.=E7=BF=BB=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D.md=20jav?= =?UTF-8?q?a=20=E7=89=88=E6=9C=AC=EF=BC=8C=E5=A2=9E=E5=8A=A0=E8=A7=A3?= =?UTF-8?q?=E6=B3=95=E5=9B=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 时间复杂度 O(n) 参考卡哥 c++ 代码的实现:先移除多余空格,再将整个字符串反转,最后把单词逐个反转 --- problems/0151.翻转字符串里的单词.md | 68 ++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index a848d6a3..5a8f8094 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -360,6 +360,74 @@ class Solution { } ``` +```java +/* + * 解法四:时间复杂度 O(n) + * 参考卡哥 c++ 代码的实现:先移除多余空格,再将整个字符串反转,最后把单词逐个反转 + */ +class Solution { + //用 char[] 来实现 String 的 removeExtraSpaces,reverse 操作 + public String reverseWords(String s) { + char[] chars = s.toCharArray(); + //1.去除首尾以及中间多余空格 + chars = removeExtraSpaces(chars); + //2.整个字符串反转 + reverse(chars, 0, chars.length - 1); + //3.单词反转 + reverseEachWord(chars); + return new String(chars); + } + + //1.用 快慢指针 去除首尾以及中间多余空格,可参考数组元素移除的题解 + public char[] removeExtraSpaces(char[] chars) { + int slow = 0; + for (int fast = 0; fast < chars.length; fast++) { + //先用 fast 移除所有空格 + if (chars[fast] != ' ') { + //在用 slow 加空格。 除第一个单词外,单词末尾要加空格 + if (slow != 0) + chars[slow++] = ' '; + //fast 遇到空格或遍历到字符串末尾,就证明遍历完一个单词了 + while (fast < chars.length && chars[fast] != ' ') + chars[slow++] = chars[fast++]; + } + } + //相当于 c++ 里的 resize() + 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--; + } + } + + //3.单词反转 + public void reverseEachWord(char[] chars) { + int start = 0; + //end <= s.length() 这里的 = ,是为了让 end 永远指向单词末尾后一个位置,这样 reverse 的实参更好设置 + for (int end = 0; end <= chars.length; end++) { + // end 每次到单词末尾后的空格或串尾,开始反转单词 + if (end == chars.length || chars[end] == ' ') { + reverse(chars, start, end - 1); + start = end + 1; + } + } + } +} +``` + python: ```Python