2024. 考试的最大困扰度题解
题目来源:2024. 考试的最大困扰度
2022.03.29每日一题
LeetCode 题解持续更新中Github仓库地址 CSDN博客地址
今天的题目使用滑动窗口的思想来做
首先根据题意,我们可以将结果拆分为 连续 T
和连续F
的个数,分别进行统计,最后取两者的最大值
题目之中给定了一个限制 k
,我们需要在窗口内统计 不同字符的个数,将其改成相同的字符,而这个次数不能超过给定的范围k
,因此,我们可以通过这个范围k
,进行控制滑动窗口的大小
class Solution {
public:
int maxConsecutiveAnswers(string answerKey, int k) {
// 返回 T 和 F 的最大值
return max(cnt(answerKey, k, 'T'), cnt(answerKey, k, 'F'));
}
int cnt(string &answerKey, int k, char ch) {
// 创建变量统计窗口的最大值
int tableMax = 0;
// 创建变量统计窗口中不同字符的个数
int differSum = 0;
int n = answerKey.length();
// 创建左右两个指针开始进行窗口的移动
for (int i = 0, j = 0; j < n; j++) {
// 统计窗口中与 ch 字符不同的个数
// 这个不同就是我们要更改的字符
if (answerKey[j] != ch) differSum++;
// 如果不同的个数大于我们所给定的范围 k
// 就需要我们右移左节点,直到我们窗口内的不同字符的个数小于等于 k
while (differSum > k) {
differSum -= answerKey[i] != ch ? 1 : 0;
++i;
}
// 取得此次窗口的最大值
tableMax = max(tableMax, j - i + 1);
}
// 并且进行返回
return tableMax;
}
};
class Solution {
public int maxConsecutiveAnswers(String answerKey, int k) {
// 返回 T 和 F 的最大值
return Math.max(cnt(answerKey, k, 'T'), cnt(answerKey, k, 'F'));
}
public int cnt(String answerKey, int k, char ch) {
// 创建变量统计窗口的最大值
int tableMax = 0;
// 创建变量统计窗口中不同字符的个数
int differSum = 0;
int n = answerKey.length();
// 创建左右两个指针开始进行窗口的移动
for (int i = 0, j = 0; j < n; j++) {
// 统计窗口中与 ch 字符不同的个数
// 这个不同就是我们要更改的字符
if (answerKey.charAt(j) != ch) differSum++;
// 如果不同的个数大于我们所给定的范围 k
// 就需要我们右移左节点,直到我们窗口内的不同字符的个数小于等于 k
while (differSum > k) {
differSum -= answerKey.charAt(i) != ch ? 1 : 0;
++i;
}
// 取得此次窗口的最大值
tableMax = Math.max(tableMax, j - i + 1);
}
// 并且进行返回
return tableMax;
}
}
- 时间复杂度 O(n)
- 空间复杂度 O(1)