Skip to content

1234. Replace the Substring for Balanced String 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int balancedString(string s) {
    const int n = s.length();
    const int k = n / 4;
    int ans = n;
    vector<int> count(128);

    for (const char c : s)
      ++count[c];

    for (int i = 0, j = 0; i < n; ++i) {
      --count[s[i]];
      while (j < n && count['Q'] <= k && count['W'] <= k && count['E'] <= k &&
             count['R'] <= k) {
        ans = min(ans, i - j + 1);
        ++count[s[j]];
        ++j;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int balancedString(String s) {
    final int n = s.length();
    final int k = n / 4;
    int ans = n;
    int[] count = new int[128];

    for (final char c : s.toCharArray())
      ++count[c];

    for (int i = 0, j = 0; i < n; ++i) {
      --count[s.charAt(i)];
      while (j < n && count['Q'] <= k && count['W'] <= k && count['E'] <= k && count['R'] <= k) {
        ans = Math.min(ans, i - j + 1);
        ++count[s.charAt(j)];
        ++j;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def balancedString(self, s: str) -> int:
    ans = len(s)
    count = Counter(s)
    j = 0

    for i, c in enumerate(s):
      count[c] -= 1
      while j < len(s) and all(count[c] <= len(s) // 4 for c in 'QWER'):
        ans = min(ans, i - j + 1)
        count[s[j]] += 1
        j += 1

    return ans