LeetCode 1234. Replace the Substring for Balanced String
原题链接在这里:https://leetcode.com/problems/replace-the-substring-for-balanced-string/
题目:
You are given a string containing only 4 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.
Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s
balanced.
Return 0 if the string is already balanced.
Example 1:
Input: s = "QWER" Output: 0 Explanation: s is already balanced.
Example 2:
Input: s = "QQWE" Output: 1 Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW" Output: 2 Explanation: We can replace the first "QQ" to "ER".
Example 4:
Input: s = "QQQQ" Output: 3 Explanation: We can replace the last 3 'Q' to make s = "QWER".
Constraints:
1 <= s.length <= 10^5
s.length
is a multiple of4
s
contains only'Q'
,'W'
,'E'
and'R'
.
题解:
n = s.length(). If s is balanced, then count of each of Q, W, E, R should be n/4.
The question is asking for minimum length, then it could be sliding window.
We don't need to chare about inside sliding window. We care about outside sliding window.
If count of one of 4 chars is > n/4, then no matter how we replace the chars inside the window, the count of this char is always > n/4.
Thus when doing sliding window, we care about the count of 4 chars, they can't be over n/4.
In order to do that, we need to get count for each char for the whole s first.
Thne runner minus the count by 1.
while the count of 4 chars <=k, update minimum lenth, move walker to increase count by 1.
here walker could be larger than runner.
e.g. "QWER". When walker == runner, all 4 count == 1. minmum length is updated to 0, and move the walker.
Now walker is past runner, but since walker pointing count == 2 now. It won't update the minimum length. Have to move the runner to minus count.
Time Complexity: O(n). n = s.length.
Space: O(1).
AC Java:
1 class Solution { 2 public int balancedString(String s) { 3 if(s== null || s.length() == 0){ 4 return 0; 5 } 6 7 int n = s.length(); 8 int k = n/4; 9 int [] map = new int[256]; 10 for(char c : s.toCharArray()){ 11 map[c]++; 12 } 13 14 int walker = 0; 15 int runner = 0; 16 int res = n; 17 while(runner < n){ 18 map[s.charAt(runner++)]--; 19 while(walker<n && map['Q']<=k && map['W']<=k && map['R']<=k && map['E']<=k){ 20 res = Math.min(res, runner-walker); 21 map[s.charAt(walker++)]++; 22 } 23 } 24 25 return res; 26 } 27 }