zoukankan      html  css  js  c++  java
  • 所有元音按顺序排不的最长子字符串 滑动窗口,聪明解法

    滑动窗口:

    //滑动窗口
    
    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;
        }
    };
    每天进步一点点~
  • 相关阅读:
    dubbo源码解析-spi(3)
    dubbo源码解析-spi(二)
    dubbo源码解析-spi(一)
    java-nio之zero copy深入分析
    Java SPI(Service Provider Interface)简介
    分析 Java heap dump工具之IBM HeapAnalyzer
    深入理解分布式事务
    NIO中的heap Buffer和direct Buffer区别
    Guava之Iterables使用示例
    Android开发中常见的设计模式 MD
  • 原文地址:https://www.cnblogs.com/libin123/p/14700411.html
Copyright © 2011-2022 走看看