[LeetCode] 151、翻转字符串里的单词

题目描述

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

输入: "  hello   world!  "   // 去除头尾空格和单词中间的多余空格
输出: "world! hello"

解题思路

比“《剑指offer》第58题”多了去除头尾空格和单词中间的多余空格这两个步骤。

参考代码

class Solution {
public:
    string reverseWords(string str) {
        string res = str;
        int length = str.length();
        if(length == 0)
            return res;

        mReverse(res, 0, length-1);

        int start = 0;
        for (int i = 0; i < res.length(); i++) {
            if (res[i] == ' ') {
                mReverse(res, start, i - 1);
                start = i + 1;//更新初始位置,变为‘ ’后面的一个字符
            }
        }      
        mReverse(res, start, res.length()-1);//对最后一个单词的反转
        
        // 去前后空格
        int left = 0;
        while(left < res.size() && res[left] == ' ') left++;
        int right = res.size() - 1;
        while(right >= 0 && res[right] == ' ') right--;
        res = res.substr(left, right-left+1);
        // 去中间多余空格
        int tail = 0;
        for(int i = 0; i < res.size(); i++){
            if(i < res.size()-1 && res[i] == ' ' && res[i+1] == ' ')
                continue;
            res[tail++] = res[i];
        }
        
        return res.substr(0, tail);
    }

    void mReverse(string &str, int low, int high){
        while(low < high){
            swap(str[low], str[high]);
            low++;
            high--;
        }
    }

};
发布了402 篇原创文章 · 获赞 588 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/ft_sunshine/article/details/104010726