在指定字符的情况下,我们可以计算其最大连续数目。具体地,我们使用滑动窗口的方法,从左到右枚举右端点,维护区间中另一种字符的数量为 sum,当 sum 超过 k,我们需要让左端点右移,直到 sum} \leq k。移动过程中,我们记录滑动窗口的最大长度,即为指定字符的最大连续数目。
本题的答案为分别指定字符为 T 和 F 时的最大连续数目的较大值。
代码
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defmaxConsecutiveAnswers(self, answerKey: str, k: int) -> int: defmaxConsecutiveChar(ch: str) -> int: ans, left, sum = 0, 0, 0 for right inrange(len(answerKey)): sum += answerKey[right] != ch whilesum > k: sum -= answerKey[left] != ch left += 1 ans = max(ans, right - left + 1) return ans returnmax(maxConsecutiveChar('T'), maxConsecutiveChar('F'))
classSolution { public: intmaxConsecutiveChar(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[right] != ch; while (sum > k) { sum -= answerKey[left++] != ch; } ans = max(ans, right - left + 1); } return ans; }
publicintMaxConsecutiveChar(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[right] != ch ? 1 : 0; while (sum > k) { sum -= answerKey[left++] != ch ? 1 : 0; } ans = Math.Max(ans, right - left + 1); } return ans; } }
intmaxConsecutiveChar(constchar * answerKey, int k, char ch) { int n = strlen(answerKey); int ans = 0; for (int left = 0, right = 0, sum = 0; right < n; right++) { sum += answerKey[right] != ch; while (sum > k) { sum -= answerKey[left++] != ch; } ans = MAX(ans, right - left + 1); } return ans; }
intmaxConsecutiveAnswers(char * answerKey, int k) { int cnt1 = maxConsecutiveChar(answerKey, k, 'T'); int cnt2 = maxConsecutiveChar(answerKey, k, 'F'); return MAX(cnt1, cnt2); }
constmaxConsecutiveChar = (answerKey, k, ch) => { const n = answerKey.length; let ans = 0; for (let left = 0, right = 0, sum = 0; right < n; right++) { sum += answerKey.charAt(right) !== ch ? 1 : 0; while (sum > k) { sum -= answerKey[left++] !== ch ? 1 : 0; } ans = Math.max(ans, right - left + 1); } return ans; };
funcmaxConsecutiveChar(answerKey string, k int, ch byte) (ans int) { left, sum := 0, 0 for right := range answerKey { if answerKey[right] != ch { sum++ } for sum > k { if answerKey[left] != ch { sum-- } left++ } ans = max(ans, right-left+1) } return }