给你一个由字符 'a'
、'b'
、'c'
组成的字符串 s
和一个非负整数 k
。每分钟,你可以选择取走 s
最左侧 还是 最右侧 的那个字符。
你必须取走每种字符 至少 k
个,返回需要的 最少 分钟数;如果无法取到,则返回-1
。
示例 1:
输入:s = "aabaaaacaabc", k = 2 输出:8 解释: 从 s 的左侧取三个字符,现在共取到两个字符 'a' 、一个字符 'b' 。 从 s 的右侧取五个字符,现在共取到四个字符 'a' 、两个字符 'b' 和两个字符 'c' 。 共需要 3 + 5 = 8 分钟。 可以证明需要的最少分钟数是 8 。
示例 2:
输入:s = "a", k = 1 输出:-1 解释:无法取到一个字符 'b' 或者 'c',所以返回 -1 。
提示:
1 <= s.length <= 10^5
s
仅由字母'a'
、'b'
、'c'
组成0 <= k <= s.length
提示 1
Start by counting the frequency of each character and checking if it is possible.
提示 2
If you take x characters from the left side, what is the minimum number of characters you need to take from the right side? Find this for all values of x in the range 0 ≤ x ≤ s.length.
提示 3
Use a two-pointers approach to avoid computing the same information multiple times.
解法:滑动窗口
必须取走每种字符 至少 k
个,也就是必须取走字符 'a'
、'b'
、'c'
每种字符都要 至少 k
个。
class Solution {
public int takeCharacters(String s, int k) {
int n = s.length();
if (n < 3 * k) {
return -1;
}
// 记录滑动窗口的长度
int ans = 0;
// 记录滑动窗口外每种字符的个数
int[] outWindow = new int[3];
int left = 0;
int right = 0;
for (int i = 0; i < n; i++) {
outWindow[s.charAt(i) - 'a']++;
}
if (outWindow[0] < k || outWindow[1] < k || outWindow[2] < k) {
return -1;
}
while (right < n) {
outWindow[s.charAt(right) - 'a']--;
while (outWindow[0] < k || outWindow[1] < k || outWindow[2] < k) {
outWindow[s.charAt(left) - 'a']++;
left++;
}
// 滑动窗口外的字符是最终取走的字符,滑动窗口越长,需要取走的字符越少
ans = Math.max(ans, right - left + 1);
right++;
}
return n - ans;
}
}
复杂度分析
- 时间复杂度:O(n),n 是 字符串s 的长度。
- 空间复杂度:O(1)。