(Leetcode) [String] Longest repeating character replacement

Topic: String
Difficulty: Medium


Question

Given a string s and an integer k, you can choose any character of the string and change it to any other uppercase English character at most k times.
Return the length of the longest substring containing the same lteer you can get after perfoming the above operations.

์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์—์„œ, ์•ŒํŒŒ๋ฒณ k๊ฐœ๋ฅผ ์ œ์ผ ๊ธด ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ด ๋‚˜์˜ค๊ฒŒ๋” ๋ฐ”๊ฟ”์„œ ๊ทธ์˜ ๊ธธ์ด๋ฅผ ๋ฆฌํ„ดํ•ด๋ผ.


Solution: Window slicing method

์ „ํ˜€ ๊ฐ์ด ์˜ค์ง€ ์•Š์•„์„œ geeksforgeeks์™€ ์œ ํŠœ๋ธŒ๋ฅผ ์ฐพ์•„๋ณด์•˜๋‹ค.
Window sliding method๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.
arr ๋ฐฐ์—ด์€ window ์•ˆ์— ์žˆ๋Š” ํŠน์ • ๊ธ€์ž์˜ ๊ฐฏ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๊ธฐ ์œ„ํ•จ์ด๋‹ค. ๊ทธ๋ž˜์„œ ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋Š” ์•ŒํŒŒ๋ฒณ์˜ ์ด ๊ฐœ์ˆ˜ (26๊ฐœ)์ด๋‹ค.

window์˜ ์˜ค๋ฅธ์ชฝ index๋ฅผ for loop์„ ์ด์šฉํ•ด ๋Š˜๋ ค์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ•œ๋‹ค.
์ฐฝ๋ฌธ ์•ˆ์— ์žˆ๋Š” ๊ฐ€์žฅ ๋งŽ์ด ๋ฐ˜๋ณต๋˜๋Š” ์•ŒํŒŒ๋ฒณ์œผ๋กœ ๋‚˜๋จธ์ง€ ๋‹ค๋ฅธ ์•ŒํŒŒ๋ฒณ์„ ๋ฐ”๊ฟ”์ฃผ๋Š”๊ฒŒ ๊ฐ€์žฅ ํšจ์œจ์ ์œผ๋กœ longest repeating substring์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.
๊ทธ๋ž˜์„œ int newlyAddedCharNum์— ์ƒˆ๋กœ์ด ๋ฐ”๋€Œ์–ด์•ผ ํ•˜๋Š” ์•ŒํŒŒ๋ฒณ์˜ ๊ฐฏ์ˆ˜๋ฅผ ์ €์žฅํ•œ๋‹ค.
newlyAddedCharNum (๋ฐ”๋€Œ์–ด์•ผ ํ•˜๋Š” ์•ŒํŒŒ๋ฒณ์˜ ๊ฐฏ์ˆ˜)๊ฐ€ k๋ณด๋‹ค ํฌ๋ฉด, ์™ผ์ชฝ index๋ฅผ ํ•œ ์นธ ์˜ฎ๊ธด๋‹ค. ๊ทธ๋Ÿฌ๋ฉด์„œ ์ฐฝ๋ฌธ ๋ฐ–์œผ๋กœ ๋‚˜๊ฐ€ ๋–จ์–ด์ง„ ์•ŒํŒŒ๋ฒณ์˜ ๊ฐœ์ˆ˜๋ฅผ ํ•˜๋‚˜ ์ค„์ธ๋‹ค.

int characterReplacement(string s, int k) {
    int result = 0;
    int leftInd = 0;
    int arr[26] = { };
    int windowSize;

    for (int j=0; j<s.length(); j++) {
        // as window enlarges, increment the number of newly added character
        arr[s[j]-'A']++;

        // saves the number of characters that needs to be changed to obtain the longest repeating substring
        int newlyAddedCharNum = j-leftInd+1 - *max_element(arr, arr+26);
        if (newlyAddedCharNum > k) {
            arr[s[leftInd]-'A']--;
            leftInd++;
        }

        result = max(result, j-leftInd+1);
    }
    return result;
}

longest-repeating-character-replacement1.jpg longest-repeating-character-replacement2.jpg


Summary

์ €๋ฒˆ์—๋„ window sliding ๋ฐฉ๋ฒ•์„ ์ผ์—ˆ๋Š”๋ฐ ์–ธ์ œ์˜€์ง€.


References

https://www.youtube.com/watch?v=gqXU1UyA8pk

Categories:

Updated:

Leave a comment