Problem: 1234. 替换子串得到平衡字符串
文章目录
- 思路
- 解题方法
- 复杂度
- Code
思路
这是一个滑动窗口问题。我们需要找到一个最小的子串,使得将其替换后,字符串中四种字符 ‘Q’, ‘W’, ‘E’, ‘R’ 的数量相等。我们可以通过滑动窗口的方式,找到一个子串,使得其外部的字符数量满足平衡条件。
解题方法
我们首先统计字符串中四种字符的数量,然后计算出每种字符应有的数量(字符串长度的四分之一)。然后我们使用两个指针 l 和 r,表示当前的窗口范围。我们不断地向右移动 r,直到窗口外的字符数量满足平衡条件。然后我们尝试向右移动 l,看看是否仍然满足平衡条件。如果满足,那么我们就找到了一个更小的满足条件的子串。我们不断重复这个过程,直到找到最小的满足条件的子串。
复杂度
时间复杂度:
O ( n ) O(n) O(n),我们需要遍历整个字符串。
空间复杂度:
O ( 1 ) O(1) O(1),我们只需要常数级别的空间来存储字符的数量。
Code
class Solution {public static int balancedString(String str) {int n = str.length();int[] arr = new int[n];int[] cnts = new int[4];for (int i = 0; i < n; i++) {char c = str.charAt(i);arr[i] = c == 'W' ? 1 : (c == 'E' ? 2 : (c == 'R' ? 3 : 0));cnts[arr[i]]++;}int require = n / 4; // 每种字符串需要的长度int ans = n; // 需要修改的长度for (int l = 0, r = 0; l < n; l++) {while (!ok(cnts, r - l, require) && r < n) {cnts[arr[r++]]--;}if (ok(cnts, r - l, require)) {ans = Math.min(ans, r - l);}cnts[arr[l]]++;}return ans;}private static boolean ok(int[] cnts, int len, int require) {for(int i = 0; i < 4; i++) {if(cnts[i] > require) {return false;}len -= require - cnts[i];}return len == 0;}}