395. Longest Substring with At Least K Repeating Characters

JJ·2021년 1월 10일
0

Algorithms

목록 보기
59/114
class Solution {
    public int longestSubstring(String s, int k) {
        int[] count = new int[26];
        
        for (int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a']++;
        }
        
        int longest = s.length(); 
        
        for (int j = s.length() - 1; j >= 0; j--) {
            int l = 0;
            while (l < count.length) {
                if (count[l] != 0 && count[l] < k) break;
                else l++;
            }
            
            if (l < count.length) {
                count[s.charAt(j) - 'a']--;
            } else {
                return j;
            }
            
        }
        
        return 0; 
    }
}

틀렸음

class Solution {
    public int longestSubstring(String s, int k) {
        if (s == null || s.isEmpty() || k > s.length()) {
            return 0;
        }
        int[] countMap = new int[26];
        int n = s.length();
        int result = 0;
        for (int start = 0; start < n; start++) {
            // reset the count map
            Arrays.fill(countMap, 0);
            for (int end = start; end < n; end++) {
                countMap[s.charAt(end) - 'a']++;
                if (isValid(s, start, end, k, countMap)) {
                    result = Math.max(result, end - start + 1);
                }
            }
        }
        return result;
    }

    private boolean isValid(String s, int start, int end, int k, int[] countMap) {
        int countLetters = 0, countAtLeastK = 0;
        for (int freq : countMap) {
            if (freq > 0) countLetters++;
            if (freq >= k) countAtLeastK++;
        }
        return countAtLeastK == countLetters;
    }
}

루션이 하이루~^^

class Solution {
    public int longestSubstring(String s, int k) {
        return longestSubstringUtil(s, 0, s.length(), k);
    }

    int longestSubstringUtil(String s, int start, int end, int k) {
        if (end < k) return 0;
        int[] countMap = new int[26];
        // update the countMap with the count of each character
        for (int i = start; i < end; i++)
            countMap[s.charAt(i) - 'a']++;
        for (int mid = start; mid < end; mid++) {
            if (countMap[s.charAt(mid) - 'a'] >= k) continue;
            int midNext = mid + 1;
            while (midNext < end && countMap[s.charAt(midNext) - 'a'] < k) midNext++;
            return Math.max(longestSubstringUtil(s, start, mid, k),
                    longestSubstringUtil(s, midNext, end, k));
        }
        return (end - start);
    }
}

Runtime: 1 ms, faster than 78.91% of Java online submissions for Longest Substring with At Least K Repeating Characters.
Memory Usage: 38.2 MB, less than 55.43% of Java online submissions for Longest Substring with At Least K Repeating Characters.

0개의 댓글