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:02https://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;
}
}
'언어 > JAVA' 카테고리의 다른 글
[Java] Daily LeetCode Challenge 103. Binary Tree Zigzag Level Order Traversal (0) | 2023.02.19 |
---|---|
[Java] Daily LeetCode Challenge 226. Invert Binary Tree (0) | 2023.02.18 |
[Java] Daily LeetCode Challenge 783. Minimum Distance Between BST Nodes (0) | 2023.02.17 |
[Java] Daily LeetCode Challenge 67. Add Binary (0) | 2023.02.14 |
[Java] Daily LeetCode Challenge 2306. Naming a Company (0) | 2023.02.09 |
Comments