[LeetCode] Longest Repeating Character Replacement 最長重複字元置換

來源:互聯網
上載者:User

標籤:div   contain   repeat   匯總   --   turn   ase   lines   post   

 

Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.

Note:
Both the string‘s length and k will not exceed 104.

Example 1:

Input:s = "ABAB", k = 2Output:4Explanation:Replace the two ‘A‘s with two ‘B‘s or vice versa.

Example 2:

Input:s = "AABABBA", k = 1Output:4Explanation:Replace the one ‘A‘ in the middle with ‘B‘ and form "AABBBBA".The substring "BBBB" has the longest repeating letters, which is 4.

 

這道題給我們了一個字串,說我們有k次隨意置換任一字元的機會,讓我們找出最長的重複字元的字串。這道題跟之前那道Longest Substring with At Most K Distinct Characters很像,都需要用滑動視窗Sliding Window來解。我們首先來想,如果沒有k的限制,讓我們求把字串變成只有一個字元重複的字串需要的最小置換次數,那麼就是字串的總長度減去出現次數最多的字元的個數。如果加上k的限制,我們其實就是求滿足(子字串的長度減去出現次數最多的字元個數)<=k的最大子字串長度即可,搞清了這一點,我們也就應該知道怎麼用滑動視窗來解了吧我們用一個變數start記錄滑動視窗左邊界,初始化為0,然後我們遍曆字串,每次累加出現字元的個數,然後更新出現最多字元的個數,然後我們判斷當前滑動視窗是否滿足之前說的那個條件,如果不滿足,我們就把滑動視窗左邊界向右移動一個,並注意去掉的字元要在counts裡減一,直到滿足條件,我們更新結果res即可,參見代碼如下:

 

class Solution {public:    int characterReplacement(string s, int k) {        int res = 0, maxCnt = 0, start = 0;        vector<int> counts(26, 0);        for (int i = 0; i < s.size(); ++i) {            maxCnt = max(maxCnt, ++counts[s[i] - ‘A‘]);            while (i - start + 1 - maxCnt > k) {                --counts[s[start] - ‘A‘];                ++start;            }            res = max(res, i - start + 1);        }        return res;    }};

 

類似題目:

Longest Substring with At Least K Repeating Characters

Longest Substring with At Most K Distinct Characters

Longest Substring with At Most Two Distinct Characters

Longest Substring Without Repeating Characters

 

參考資料:

https://discuss.leetcode.com/topic/63494/java-12-lines-o-n-sliding-window-solution-with-explanation/2

https://discuss.leetcode.com/topic/63416/sliding-window-similar-to-finding-longest-substring-with-k-distinct-characters/2

 

LeetCode All in One 題目講解匯總(持續更新中...)

[LeetCode] Longest Repeating Character Replacement 最長重複字元置換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.