Leetcode 1234
题目描述
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".
方法
** Solution Java **
** 6ms, beats 89.37% **
** 39.9MB, beats 100.00% **
class Solution {
public int balancedString(String s) {
int n = s.length(), res = n, k = n/4;
int[] count = new int[128];
for (int i = 0; i < n; ++i)
++count[s.charAt(i)];
for (int i = 0, j = 0; j < n; ++j) {
--count[s.charAt(j)];
while (i < n && count['Q'] <= k && count['W'] <= k && count['E'] <= k && count['R'] <= k) {
res = Math.min(res, j - i + 1);
++count[s.charAt(i++)];
}
}
return res;
}
}
使用charArray索引将比charAt()快
** 4ms, beats 100.00% **
** 40.7MB, beats 100.00% **
class Solution {
public int balancedString(String s) {
int n = s.length(), res = n, k = n/4;
int[] count = new int[128];
char[] S = s.toCharArray();
for (int i = 0; i < n; ++i)
++count[S[i]];
for (int i = 0, j = 0; j < n; ++j) {
--count[S[j]];
while (i < n && count['Q'] <= k && count['W'] <= k && count['E'] <= k && count['R'] <= k) {
res = Math.min(res, j - i + 1);
++count[S[i++]];
}
}
return res;
}
}
** Solution Python3 **
** 476ms, 18.93% **
** 13.6MB, 100.00% **
class Solution:
def balancedString(self, s):
count = collections.Counter(s)
res = n = len(s)
i = 0
for j, c in enumerate(s):
count[c] -= 1
while i < n and all(n / 4 >= count[c] for c in 'QWER'):
res = min(res, j - i + 1)
count[s[i]] += 1
i += 1
return res