滑动窗口:
//滑动窗口 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; } };