32ms C++


  • 0
    B
    class Solution {
    public:
        int characterReplacement(string s, int k)
        {
            int ans=0;
            int ls=s.size();
            vector<char> letters;
            int flag[30]={0};
            for(int i=0;i<ls;i++)
                flag[s[i]-'A']=1;
            for(int i=0;i<26;i++)
                if (flag[i]>0) letters.push_back(i+'A');
            int lletters=letters.size();
            for(int i=0;i<lletters;i++)
            {
                int head=0,tail,leftk=k;
                // head is the first letter of substring
                // tail is the one trying to envolve
                if (s[head]!=letters[i])
                {
                    if (leftk>0) leftk--;
                    else
                    {
                        while (head<ls && s[head]!=letters[i]) head++;
                    }
                }
                tail=head+1;
                while(tail<ls)
                {
                    if (s[tail]!=letters[i])
                    {
                        if (leftk>0)
                            leftk--;
                        else
                        {
                            while(s[head]==letters[i]) head++;
                            head++;
                        }
                    }
                    ans=max(ans,(tail-head+1));
                    tail++;
                }
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.