LeetCode-424. 替換後的最長重複字符

地址:https://leetcode-cn.com/problems/longest-repeating-character-replacement/

思路:思維

遍歷子串的右端點r,同時記錄過程中所滿足條件的最大相同字符個數Max,對於r-l-Max>k的情況,則右移左端點l直至滿足條件,最後保留最大值r-l即可

Code:

#include<iostream>
using namespace std;

class Solution {
public:
    int characterReplacement(string s, int k) {
        int a[30]={0},n=s.length();
        int res=0,Max=0,l=-1,r=0;
        while(r<n){
			++a[s[r]-'A'];
			Max=max(Max,a[s[r]-'A']);
			while(r-l-Max>k){
				--a[s[++l]-'A'];
			}
			res=max(res,r-l);
			++r;
		}
		return res;
    }
};

int main()
{
	ios::sync_with_stdio(false);
	int m;
	string s;
	Solution So;
	cin>>s>>m;
	int res=So.characterReplacement(s,m);
	cout<<res<<endl;
	
	return 0;
}

 

發佈了325 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章