• 所有元音按顺序排不的最长子字符串 滑动窗口,聪明解法


    滑动窗口:

    //滑动窗口
    
    class Solution {
    public:
        int longestBeautifulSubstring(string word) {
            vector<char> window; 
            unordered_set<char> cnt;//记录字符种类
            int res = 0;
    
            int left = 0, right = 0;
    
            while (right < word.length()) {
                //窗口右扩
                if (window.empty() || word[right] >= window.back()) {
                    window.push_back(word[right]);
                    cnt.insert(word[right]);
                    if (cnt.size() == 5) {
                        res = max(res, (int)window.size());
                    }
                }
                //窗口左侧收缩  跳到当前字符 
                else {
                    window.clear();
                    cnt.clear();
                    left = right;//
                    window.push_back(word[left]);
                    cnt.insert(word[left]);
                }
                right++;
            }
    
            return res;
        }
    };
    //因为只要有两个条件,字典序排列和包含五种元音,所以直接依次遍历
    
    //如果比较失败,就从当前字符开始,不用回到前面,因为回到前面到了这里又会比较失败且长度不会超过从最初位置开始的长度 类似于窗口的直接清空
    class Solution {
    public:
        int longestBeautifulSubstring(string word) {
            if (word.size()<5)return 0;
            int res=0;
            int rlen=1;
            int vowel=1;
            for(int i=1;i<word.length();i++){
                if(word[i]>=word[i-1])rlen++;//字符数增加
                if(word[i]>word[i-1])vowel++; //增加种类数
                if(word[i]<word[i-1]){rlen=1;vowel=1;}
                if(vowel==5){res=rlen>res?rlen:res;}
            }
            return res;
        }
    };
    每天进步一点点~
  • 相关阅读:
    Java_基础_内存管理
    Reflux中文教程——action
    Reflux中文教程——概览
    包含块、层叠上下文、BFC
    DOM编程的性能问题
    JavaScript数据存取的性能问题
    闭包
    JavaScript中的继承
    JavaScript中的静态成员
    JavaScript中的私有属性
  • 原文地址:https://www.cnblogs.com/libin123/p/14700411.html
Copyright © 2020-2023  润新知