LeetCode 1234. Replace the Substring for Balanced String

时间:2024-12-06 22:06:32

原题链接在这里: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 of 4
  • 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:

 class Solution {
public int balancedString(String s) {
if(s== null || s.length() == 0){
return 0;
} int n = s.length();
int k = n/4;
int [] map = new int[256];
for(char c : s.toCharArray()){
map[c]++;
} int walker = 0;
int runner = 0;
int res = n;
while(runner < n){
map[s.charAt(runner++)]--;
while(walker<n && map['Q']<=k && map['W']<=k && map['R']<=k && map['E']<=k){
res = Math.min(res, runner-walker);
map[s.charAt(walker++)]++;
}
} return res;
}
}

类似Minimum Window Substring.