[leetCode]151. 翻转字符串里的单词

csdn:https://blog.csdn.net/renweiyi1487/article/details/109336278

题目

给定一个字符串,逐个翻转字符串中的每个单词。

说明:

无空格字符构成一个 单词 。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

示例 1:

输入:"the sky is blue"
输出:"blue is sky the"
示例 2:

输入:"  hello world!  "
输出:"world! hello"
解释:输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:

输入:"a good   example"
输出:"example good a"
解释:如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
示例 4:

输入:s = "  Bob    Loves  Alice   "
输出:"Alice Loves Bob"
示例 5:

输入:s = "Alice does not even like bob"
输出:"bob like even not does Alice"
 

提示:

1 <= s.length <= 104
s 包含英文大小写字母、数字和空格 ' '
s 中 至少存在一个 单词

思路

  1. 先去除字符串当中多余的空格
  2. 将整个字符串反转
  3. 将字符串中的单词反转
class Solution {
    public String reverseWords(String s) {
        char[] chars = s.toCharArray();
        chars = removeExtraSpace(chars);
        reverse(chars, 0, chars.length - 1);
        int begin = 0, end = 0;
        while (end < chars.length) {
            if (chars[end] == ' ') {
                reverse(chars, begin, end - 1);
                begin = end + 1;
            }
            end++;
        }
        reverse(chars, begin, chars.length - 1);
        return new String(chars);
    }

    private char[] removeExtraSpace(char[] chars) {
        int n = chars.length;
        int fastIndex = 0, slowIndex = 0;
        // 跳过字符串开头的空格
        while (fastIndex < n && chars[fastIndex] == ' ') {
            fastIndex++;
        }
        // 去除字符串中间的空格
        while ( fastIndex < n) {
            if (fastIndex > 0 && chars[fastIndex] == chars[fastIndex - 1] && chars[fastIndex] == ' ') {
                fastIndex ++;
                continue;
            } else {
                chars[slowIndex++] = chars[fastIndex];
            }
            fastIndex++;
        }
        // 去除字符串末尾的空格
        if (slowIndex - 1 > 0 && chars[slowIndex - 1] == ' ') {
            return Arrays.copyOf(chars, slowIndex - 1);
        } else {
            return Arrays.copyOf(chars, slowIndex);
        }
    }

    private void reverse(char[] chars, int left, int right) {
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
    }
}
posted @ 2020-10-28 16:29  消灭猕猴桃  阅读(54)  评论(0编辑  收藏  举报