diff --git a/notes/58.1 翻转单词顺序列.md b/notes/58.1 翻转单词顺序列.md index 684a5a3a..19e2c951 100644 --- a/notes/58.1 翻转单词顺序列.md +++ b/notes/58.1 翻转单词顺序列.md @@ -1,8 +1,8 @@ # 58.1 翻转单词顺序列 -## 题目描述 +## 题目链接 -[牛客网](https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3?tpId=13&tqId=11197&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) +[Leetcode](https://leetcode.cn/problems/fan-zhuan-dan-ci-shun-xu-lcof/) ## 题目描述 @@ -21,29 +21,50 @@ Output: 题目应该有一个隐含条件,就是不能用额外的空间。虽然 Java 的题目输入参数为 String 类型,需要先创建一个字符数组使得空间复杂度为 O(N),但是正确的参数类型应该和原书一样,为字符数组,并且只能使用该字符数组的空间。任何使用了额外空间的解法在面试时都会大打折扣,包括递归解法。 ```java -public String ReverseSentence(String str) { - int n = str.length(); - char[] chars = str.toCharArray(); - int i = 0, j = 0; - while (j <= n) { - if (j == n || chars[j] == ' ') { - reverse(chars, i, j - 1); - i = j + 1; - } - j++; +public String reverseMessage(String message) { + if (message == null) { + return null; } + char[] chars = message.toCharArray(); + int n = chars.length; + + // 1. 翻转整个字符数组 reverse(chars, 0, n - 1); - return new String(chars); + // 2. 翻转每个单词 + reverseWords(chars, n); + // 3. 去除多余空格 + return cleanSpaces(chars, n); +} + +private void reverseWords(char[] a, int n) { + int i = 0, j = 0; + while (i < n) { + while (i < n && a[i] == ' ') i++; + j = i; + while (j < n && a[j] != ' ') j++; + reverse(a, i, j - 1); + i = j; + } +} + +private String cleanSpaces(char[] a, int n) { + int i = 0, j = 0; + while (j < n) { + while (j < n && a[j] == ' ') j++; + while (j < n && a[j] != ' ') a[i++] = a[j++]; + while (j < n && a[j] == ' ') j++; + if (j < n) a[i++] = ' '; + } + return new String(a, 0, i); } private void reverse(char[] c, int i, int j) { - while (i < j) - swap(c, i++, j--); -} - -private void swap(char[] c, int i, int j) { - char t = c[i]; - c[i] = c[j]; - c[j] = t; + while (i < j) { + char t = c[i]; + c[i] = c[j]; + c[j] = t; + i++; + j--; + } } ```