Leetcode1839. 所有元音按顺序排布的最长子字符串

Every day a Leetcode

题目来源:1839. 所有元音按顺序排布的最长子字符串

解法1:滑动窗口

要找的是最长美丽子字符串的长度,我们可以用滑动窗口解决。

设窗口内的子字符串为 window,每当 wordright >= window.back() 时,说明可以按字典序升序排布,我们都可以将 wordright 添加进 window 的末尾,我们使用一个集合 cnt 存储每次遇到的 wordright,当 cnt.size() = 5时,说明所有 5 个英文元音字母都至少出现了一次,更新长度:max_len = max(max_len, (int)window.size())。

如果遇到了不按字典序升序排布的情况,我们发现窗口必须全部清空,于是有:window = "",cnt.clear(),同时要改变窗口的左边界 left = right,立即将 wordleft 加入进窗口和集合,重新开始遍历。

代码:

c 复制代码
/*
 * @lc app=leetcode.cn id=1839 lang=cpp
 *
 * [1839] 所有元音按顺序排布的最长子字符串
 */

// @lc code=start

// 滑动窗口

class Solution
{
public:
    int longestBeautifulSubstring(string word)
    {
        // 特判
        if (word.size() < 5)
            return 0;
        int n = word.size();
        string window;
        unordered_set<char> cnt;
        int max_len = 0, left = 0, right = 0;
        while (right < n)
        {
            if (window.empty() || word[right] >= window.back())
            {
                window += word[right];
                cnt.insert(word[right]);
                right++;
                if (cnt.size() == 5)
                    max_len = max(max_len, (int)window.size());
            }
            else
            {
                window = "";
                cnt.clear();
                left = right;
                window += word[left];
                cnt.insert(word[left]);
                right++;
            }
        }
        return max_len;
    }
};
// @lc code=end

结果:

复杂度分析:

时间复杂度:O(n),其中 n 是字符串 word 的长度。

空间复杂度:O(n),其中 n 是字符串 word 的长度。

解法2:一次遍历

由滑动窗口的启发,我们发现只设立几个变量也能达到相同的效果。

代码:

c 复制代码
class Solution
{
public:
    int longestBeautifulSubstring(string word)
    {
        // 特判
        if (word.size() < 5)
            return 0;
        int n = word.size();
        int max_len = 0;
        int vowel = 1, cur_len = 1;
        for (int i = 1; i < n; i++)
        {
            if (word[i] >= word[i - 1])
            {
                cur_len++;
                if (word[i] > word[i - 1])
                    vowel++;
            }
            else
            {
                cur_len = 1;
                vowel = 1;
            }
            if (vowel == 5)
                max_len = max(max_len, cur_len);
        }
        return max_len;
    }
};

结果:

复杂度分析:

时间复杂度:O(n),其中 n 是字符串 word 的长度。

空间复杂度:O(1)。

相关推荐
_日拱一卒14 分钟前
LeetCode:46全排列
算法·leetcode·职场和发展
剑挑星河月27 分钟前
31.下一个排列
java·算法·leetcode
凌波粒31 分钟前
LeetCode--98.验证二叉搜索树(二叉树)
算法·leetcode·职场和发展
Misnearch36 分钟前
3635. 最早完成陆地和水上游乐设施的时间II
leetcode·贪心·排序
Kurisu5751 小时前
深度拆解:从令牌桶到滑动窗口,高并发系统限流算法的数学本质与边界
java·网络·算法
哈泽尔都1 小时前
运动控制教学——5分钟学会力控算法(阻抗/导纳/力位混合)
c++·python·算法·决策树·贪心算法·机器人·gpu算力
WWW65261 小时前
代码随想录 打卡第四十七天
数据结构·算法·leetcode
cpp_25011 小时前
P10722 [GESP202406 六级] 二叉树
数据结构·c++·算法·题解·洛谷·树形结构·gesp六级
smj2302_796826521 小时前
解决leetcode第3948题字典序最大的MEX数组
python·算法·leetcode
周末也要写八哥2 小时前
浅谈:C++中cpp 14 ~ cpp 17
开发语言·c++·算法