Step-by-Step

[Java] LeetCode 395. Longest Substring with At Least K Repeating Characters 본문

언어/JAVA

[Java] LeetCode 395. Longest Substring with At Least K Repeating Characters

희주(KHJ) 2023. 2. 17. 13:02

https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/

 

Longest Substring with At Least K Repeating Characters - LeetCode

Longest Substring with At Least K Repeating Characters - Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.   Example 1: Input: s =

leetcode.com

처음에 문제 이해를 잘 못 해서 알파벳 k개만 사용하는걸로 착각했었는데,

알파벳이 몇개이든 substring 내부에 있는 모든 알파벳이 k개 이상 사용된 경우 최대 길이를 구해야 한다!

 

HashMap을 이용해서 구현

 

 

[코드]

class Solution {
    public int longestSubstring(String s, int k) {
        int ans = 0;
        for(int i=0; i<s.length(); i++){
            HashMap<Character, Integer> hm = new HashMap<>();
            for(int j=i; j<s.length(); j++){
                char ch = s.charAt(j);
                hm.put(ch, hm.getOrDefault(ch, 0)+1);

                if(isRight(hm, k))
                    ans = Math.max(ans, j-i+1);
            }
        }

        return ans;
    }

    public boolean isRight(HashMap<Character, Integer> hm, int k){
        for(char ch : hm.keySet()){
            if(hm.get(ch) < k)
                return false;
        }

        return true;
    }
}

 

 

Comments