Skip to content

Commit 0299d64

Browse files
committed
longest substring with at least k repeated characters
1 parent 1e08f7e commit 0299d64

File tree

3 files changed

+117
-38
lines changed

3 files changed

+117
-38
lines changed

.idea/workspace.xml

Lines changed: 43 additions & 38 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,3 +415,7 @@ codes may not be optimized
415415

416416
1. [LRU Cache](https://leetcode.com/problems/lru-cache/description/)
417417
1. [LFU Cache](https://leetcode.com/problems/lfu-cache/description/)
418+
419+
### Day 20 - Medium
420+
421+
1. [Longest Substring with at least k Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/description/)
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.github.chen0040.leetcode.day20.medium;
2+
3+
4+
import java.util.ArrayList;
5+
import java.util.HashMap;
6+
import java.util.List;
7+
import java.util.Map;
8+
9+
10+
/**
11+
* Created by xschen on 15/8/2017.
12+
*
13+
* link: https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/description/
14+
*/
15+
public class LongestSubstringWithAtLeastKRepeatedCharacters {
16+
public class Solution {
17+
public int longestSubstring(String s, int k) {
18+
Map<Character, Integer> counts = new HashMap<Character, Integer>();
19+
for(int i=0; i < s.length(); ++i) {
20+
char c = s.charAt(i);
21+
counts.put(c, counts.getOrDefault(c, 0) + 1);
22+
}
23+
StringBuilder sb = new StringBuilder();
24+
for(Map.Entry<Character, Integer> entry : counts.entrySet()) {
25+
if(entry.getValue().intValue() < k) {
26+
sb.append(entry.getKey());
27+
}
28+
}
29+
String lowFreqWords = sb.toString();
30+
//System.out.println(lowFreqWords);
31+
32+
List<int[]> ranges = new ArrayList<int[]>();
33+
int lo = 0;
34+
int hi = 0;
35+
if(!lowFreqWords.isEmpty()) {
36+
for(int i=0; i < s.length(); ++i) {
37+
char c = s.charAt(i);
38+
if(lowFreqWords.indexOf(c) != -1) {
39+
hi = i - 1;
40+
if(hi >= lo) {
41+
ranges.add(new int[] { lo, hi});
42+
hi = -1;
43+
}
44+
lo = i + 1;
45+
} else {
46+
hi++;
47+
}
48+
}
49+
if(hi != -1) {
50+
if(s.length()-1 >= lo){
51+
ranges.add(new int[] { lo, s.length() - 1});
52+
}
53+
}
54+
55+
int maxLen = 0;
56+
for(int[] range : ranges){
57+
//System.out.println("[" + range[0] + ", " + range[1] + "]");
58+
String s2 = s.substring(range[0], range[1] + 1);
59+
if(s2.length() < k) continue;
60+
61+
maxLen = Math.max(maxLen, longestSubstring(s2, k));
62+
}
63+
return maxLen;
64+
65+
} else {
66+
return s.length();
67+
}
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)