Share a ByteDance backend interview algorithm question

topic:

Given a string s, you can convert any character to any lowercase character. This operation can be performed m times, and the length of the longest equal substring in the converted string is asked.

case:

s="abcdac", m=2, 2 operations, can be converted to "abcccc", the longest is 4, return 4.

analyze:

The topic is easy to understand, but it is still a bit difficult for students who do not have a thorough grasp of the algorithm or who do not understand the sliding window and double-pointer algorithms. Any character of the string can be changed to another character. We prioritize sliding window double pointers to write

Define left and right as left and right pointers, and define a dictionary mpto record the number of occurrences of each character in the string. Traverse the string s once, each cycle is executed as follows, the character corresponding to the subscript element is +1, if right-left+1 (the length of the current window) - the largest number in the mp dictionary (max_value) > m, it means no It is possible to complete such an operation, subtracting the character corresponding to the current mp subscript element, left+1. Execute again right-left+1 (the length of the current window) - the largest number in the mp dictionary (max_value) > m operation, directly this judgment statement does not meet . After the end, it shows that the string of right-left+1 satisfies the operation m times to convert any character to any lowercase character. Compared with max_length, take the maximum value.

mp: Guaranteed to be the number of characters corresponding to the characters in the sliding window [left, right] of the string s

max_value: the maximum value of the number of characters in the sliding window

max_length: the longest equal substring length after m operations

Subject code:

#include<iostream>
#include<unordered_map>
using namespace std;
int main()
{
	string s;
	int m;
	cin>>s;
	cin>>m;
	unordered_map<char,int>mp;
	int left=0;
	int max_lenth=0;
	for(int right=0;right<s.size();right++)
	{
		mp[s[right]]++;
		int max_value=0;
		for(int i=0;i<26;i++)
		{
			char ch='a'+i;
			max_value=max(max_value,mp[ch]);
		}
		while(right-left+1-max_value>m)
		{
			mp[s[left]]--;
			left++;
		}
		max_lenth=max(max_lenth,right-left+1);
	}
	cout<<max_lenth<<endl;
}

Guess you like

Origin blog.csdn.net/m0_63743577/article/details/131741381