
1234. Replace the Substring for Balanced StringYou are given a string s of length n containing only four kinds of characters: ‘Q’, ‘W’, ‘E’, and ‘R’.A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.Returnthe minimum length of the substring that can be replaced with any other string of the same length to make s balanced.If s is already balanced, return 0.Example 1:Input:s “QWER”Output:0Explanation:s is already balanced.Example 2:Input:s “QQWE”Output:1Explanation:We need to replace a ‘Q’ to ‘R’, so that “RQWE” (or “QRWE”) is balanced.Example 3:Input:s “QQQW”Output:2Explanation:We can replace the first “QQ” to “ER”.Constraints:n s.length4 n 10 5 4 n 10^54n105n is a multiple of 4.s contains only ‘Q’, ‘W’, ‘E’, and ‘R’.From: LeetCodeLink: 1234. Replace the Substring for Balanced StringSolution:Ideas:use sliding window. The window is the substring we replace. Outside the window, every character count must be n / 4.Code:intbalancedString(char*s){intcnt[128]{0};intn0;while(s[n]){cnt[(int)s[n]];n;}inttargetn/4;if(cnt[Q]targetcnt[W]targetcnt[E]targetcnt[R]target){return0;}intansn;intleft0;for(intright0;rightn;right){cnt[(int)s[right]]--;while(leftrightcnt[Q]targetcnt[W]targetcnt[E]targetcnt[R]target){intlenright-left1;if(lenans)anslen;cnt[(int)s[left]];left;}}returnans;}