티스토리 뷰

728x90

 

 

class Solution {
    public int balancedString(String s) {
        //caching
        var cache = new int[128];
        int n = s.length(), result = n, k = n / 4;
        for (var ch : s.toCharArray()) {
            cache[ch]++;
        }
        //sliding windows
        var slow = 0; var fast = 0;
        while (fast < n) {
            //fast pointer goes while slow pointer condition does not meet.
            //decrease cache frequency.
            cache[s.charAt(fast)]--;
            fast++;
            
            //caused by fast pointer action(decreasing cache frequency).
            while (slow < n && cache['Q'] <= k && cache['W'] <= k && cache['E'] <= k && cache['R'] <= k) {
                //shortest window.
                result = Math.min(result, fast - slow);
                
                //revoke cache frequency.
                cache[s.charAt(slow)]++;
                slow++;
            }
        }
        return result;
    }
}

 

레퍼런스

https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/408978/JavaC%2B%2BPython-Sliding-Window

 

[Java/C++/Python] Sliding Window - LeetCode Discuss

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함