日野弥生:勉強しよう

LeetCode 151 - 反转字符串中的单词

发表于2024年12月23日

#双指针 #字符串 #正则表达式

可以先利用reverse函数把所有的字符都反转一遍,然后利用正则表达式去掉多余的空格。 其次,再把头空格和尾空格处理掉。

进入for循环,把每两个空格之间的单词进行一一反转,注意最后一个单词后没有空格,要单独翻转

class Solution {
public:
    string reverseWords(string s) {
        std::reverse(s.begin(),s.end());
        s = std::regex_replace(s, std::regex(" +"), " ");
        if(s.front()==' ')
            s=s.substr(1,s.size()-1);
        if(s.back()==' ')
            s=s.substr(0,s.size()-1);
        int lastSpace=-1;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]==' ')
            {
                int start=lastSpace+1;
                lastSpace=i;
                std::reverse(s.begin()+start,s.begin()+lastSpace);
            }
        }
        std::reverse(s.begin()+lastSpace+1,s.end());
        return s;
    }
};

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/reverse-words-in-a-string

上一篇

LeetCode 5 - 最长回文子串

下一篇

LeetCode 1 - 两数之和