LeetCode151. 颠倒字符串中的单词

题目

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"
解释:如果两个单词间有多余的空格,颠倒后的字符串需要将单词间的空格减少到仅有一个。

代码

class Solution {
    
    
public:
    void reverse(string& s, int start, int end) {
    
    
        for (int i = start, j = end; i < j; i++, j--) {
    
    
            swap(s[i], s[j]);
        }
    }

    void removeExtraSpace(string& s) {
    
    
        int slowIndex = 0, fastIndex = 0; //快慢指针
        // 让快指针略过字符串前面空格
        while (s[fastIndex] == ' ' && fastIndex < s.size() && s.size() > 0) {
    
    
            fastIndex++;
        }

        for (; fastIndex < s.size(); fastIndex++) {
    
      // 从字符串中第一个字符开始遍历
            if (fastIndex - 1 > 0 && s[fastIndex] == ' ' && s[fastIndex] == s[fastIndex-1]) {
    
    
                continue; //中间有多余空格,移除掉
            }
            else {
    
    
                s[slowIndex] = s[fastIndex]; // 将找到的字符赋值给慢指针中
                slowIndex++;
            }
        }

        if (s[slowIndex-1] == ' ' && slowIndex - 1 > 0) {
    
      //删掉末尾多余空格
            s.resize(slowIndex-1);
        }
        else {
    
    
            s.resize(slowIndex);
        }
    }

    string reverseWords(string s) {
    
    
        // 移除多余空格
        removeExtraSpace(s);
        // 反转整个字符串
        reverse(s, 0, s.length() - 1);
        // 将每个单词独立反转一下
        for (int i = 0; i < s.size(); i++) {
    
    
            int j = i;
            while (s[j] != ' ' && j < s.size()) {
    
    
                j++;
            } // j指向空格
            reverse(s, i, j - 1);
            i = j;
        }
        return s;
    }
};

猜你喜欢

转载自blog.csdn.net/Star_ID/article/details/125293959