题解: 利用滑动窗口
需要将字符串假设两种可能,一种是T解(也就是说含T的最长字符串),一种是F解(含F的最长字符串)首先遍历数组,假设为T解,那么F为另一种字符。双指针left和right,当left找到了第一个T时,right++,当遇到了F时将其计数count,当count大于2时(不是等于2)意味着此时从left开始的T字符串到现在的right已经是最长的字符串了,这时将此字符串的长度记录并放到当right为字符串结尾,假如有别的T解字符串比较长度,最后得出T解的最长字符串解,同理,求F解也是如此。当然也可以不那么麻烦分为求T解和F解,还是使用滑动窗口的方法,当right找到另一种字符的上限时,也就是当前left字符的最长字符串了,那么将left移动到以另一种字符开始的字符串,当然这样编码的话,难度会大上许多,需要细心.
最后贴上代码模板,不妨自己动手来写一下
class Solution {
public int maxConsecutiveAnswers(String answerKey, int k) {
}
}
class Solution {
public int maxConsecutiveAnswers(String answerKey, int k) {
return Math.max(maxConsecutiveChar(answerKey, k, 'T'), maxConsecutiveChar(answerKey, k, 'F'));
}
public int maxConsecutiveChar(String answerKey, int k, char ch) {
int n = answerKey.length();
int ans = 0;
for (int left = 0, right = 0, sum = 0; right < n; right++) {
sum += answerKey.charAt(right) != ch ? 1 : 0;
while (sum > k) {
sum -= answerKey.charAt(left++) != ch ? 1 : 0;
}
ans = Math.max(ans, right - left + 1);
}
return ans;
}
}
题解转自力扣官方.
在后面,我会经常更新力扣的算法题,也算是为自己监督,欢迎大家关注.还有想要说明的一点是,每次遇到中等以及hard题目,官方给的解释总是一大堆,有时候很难理解,我会用尽量好理解的方式来说明.