Skip to content

Commit bb6bc60

Browse files
committed
fd
1 parent 4f5f016 commit bb6bc60

File tree

2 files changed

+22
-38
lines changed

2 files changed

+22
-38
lines changed

solution/src/main/java/com/inuker/solution/LongestSubstringWithAtMostKDistinctCharacters.java

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,29 +11,20 @@ public class LongestSubstringWithAtMostKDistinctCharacters {
1111
/**
1212
* 思路跟Longest Substring With At Most Two Distinct Characters一样,只是给2改成k,要注意k等于0时返回0
1313
*/
14-
// 耗时9ms
1514
public int lengthOfLongestSubstringKDistinct(String s, int k) {
16-
if (k == 0) {
17-
return 0;
18-
}
19-
20-
int[] count = new int[256];
21-
int distinct = 0, longest = 0;
22-
23-
for (int i = 0, j = 0; j < s.length(); j++) {
24-
if (count[s.charAt(j)]++ == 0) {
25-
distinct++;
26-
}
27-
28-
for ( ; i < j && distinct > k; ) {
29-
if (--count[s.charAt(i++)] == 0) {
30-
--distinct;
15+
int longest = 0;
16+
int[] dp = new int[256];
17+
for (int i = 0, j = 0, n = 0; j < s.length(); j++) {
18+
char c = s.charAt(j);
19+
if (dp[c]++ == 0) {
20+
for (++n; i <= j && n > k; i++) {
21+
if (--dp[s.charAt(i)] == 0) {
22+
n--;
23+
}
3124
}
3225
}
33-
3426
longest = Math.max(longest, j - i + 1);
3527
}
36-
3728
return longest;
3829
}
3930

test/src/main/java/com/inuker/test/main.java

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -30,27 +30,20 @@ public static void main(String[] args) {
3030
test.call("how");
3131
}
3232

33-
public List<Integer> topKFrequent(int[] nums, int k) {
34-
HashMap<Integer, Integer> map = new HashMap<>();
35-
for (int n : nums) {
36-
map.put(n, map.getOrDefault(n, 0) + 1);
37-
}
38-
Queue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
39-
@Override
40-
public int compare(Integer o1, Integer o2) {
41-
return map.get(o1) - map.get(o2);
42-
}
43-
});
44-
for (Integer n : map.keySet()) {
45-
queue.add(n);
46-
if (queue.size() > k) {
47-
queue.poll();
33+
public int lengthOfLongestSubstringKDistinct(String s, int k) {
34+
int longest = 0;
35+
int[] dp = new int[256];
36+
for (int i = 0, j = 0, n = 0; j < s.length(); j++) {
37+
char c = s.charAt(j);
38+
if (dp[c]++ == 0) {
39+
for (++n; i <= j && n > k; i++) {
40+
if (--dp[s.charAt(i)] == 0) {
41+
n--;
42+
}
43+
}
4844
}
45+
longest = Math.max(longest, j - i + 1);
4946
}
50-
List<Integer> list = new LinkedList<>();
51-
while (!queue.isEmpty()) {
52-
list.add(queue.poll());
53-
}
54-
return list;
47+
return longest;
5548
}
5649
}

0 commit comments

Comments
 (0)