双指针模型

发布时间 2023-10-26 09:41:31作者: 深渊之巅

 

 

 

 

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int N = 1e6 + 10, M = 2010;

int n, m;
int a[N];
int st[M];
int ll, rr = 1e8;

int main() {
    scanf("%d%d", &n, &m);
    for(int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
    
    int l = 0, r = -1, cnt = 0;
    for(; r ++ < n;) {
        if(st[a[r]] == 0) cnt ++ ;
        st[a[r]] ++ ;
        while(st[a[l]] > 1) {
            st[a[l]] -- ;
            l ++ ;
        }
        
        if(cnt >= m) {
            if(r - l < rr - ll) {
                rr = r, ll = l;
            }
        }
    }
    
    cout << ll + 1 << ' ' << rr + 1 << endl;

    return 0;
}

 

 

 

class Solution {
public:
    int expressiveWords(string s, vector<string>& words) {
        int n = s.size();
        int res = 0;

        auto check = [&](string &s, string &p) -> bool {
            int n1 = s.size(), n2 = p.size();

            int p1 = 0, p2 = 0;
            while(p1 < n1 && p2 < n2) {
                int cnt1 = 0, cnt2 = 0;
                char c = s[p1];

                while(p1 < n1 && s[p1] == c) p1 ++ , cnt1 ++ ;
                while(p2 < n2 && p[p2] == c) p2 ++ , cnt2 ++ ;

                if(cnt1 < cnt2 || (cnt1 > cnt2 && cnt1 < 3)) return 0;
            }

            return p1 == n1 && p2 == n2;
        };

        for(auto &word: words) {
            if(check(s, word)) res ++ ;
        }

        return res;
    }
};