Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 424. Longest Repeating Character Replacement #84

Open
Woodyiiiiiii opened this issue Sep 6, 2020 · 0 comments
Open

LeetCode 424. Longest Repeating Character Replacement #84

Woodyiiiiiii opened this issue Sep 6, 2020 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Sep 6, 2020

Given a string s that consists of only uppercase English letters, you can perform at most k operations on that string.

In one operation, you can choose any character of the string and change it to any other uppercase English character.

Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations.

Note:
Both the string's length and k will not exceed 10^4.

Example 1:

Input:
s = "ABAB", k = 2

Output:
4

Explanation:
Replace the two 'A's with two 'B's or vice versa.

Example 2:

Input:
s = "AABABBA", k = 1

Output:
4

Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.

不要被k个操作疑惑了,根据连续子字符串,要想到 滑动窗口(sliding windows) 方法。

维护一个窗口,计算窗口内的最大重复字符数量,如果该数量与k的和小于窗口长度,则窗口左边界左移;这样的目的是保持窗口内最大重复字母数量加上操作k限制的操作数量等于窗口长度。

如何找出滑动窗口内出现频率最高的字母也很重要,维护一个26长度的一维数组,表示窗口内对应26个字母的出现次数,每次如果哪个字母出现次数增加,就要做一次判断找出最大频率字母。

class Solution {
    public int characterReplacement(String s, int k) {
        int res = 0, max = 0, left = 0;
        final int NUM = 26;
        int[] cnt = new int[NUM];
        for (int right = 0; right < s.length(); ++right) {
            max = Math.max(max, ++cnt[s.charAt(right) - 'A']);
            while (right - left + 1 - max > k) {
                --cnt[s.charAt(left) - 'A'];
                ++left;
            }
            res = Math.max(res, right - left + 1);
        }
        return res;
    }
}

参考资料:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant