File tree Expand file tree Collapse file tree 2 files changed +22
-38
lines changed
solution/src/main/java/com/inuker/solution
test/src/main/java/com/inuker/test Expand file tree Collapse file tree 2 files changed +22
-38
lines changed Original file line number Diff line number Diff line change @@ -11,29 +11,20 @@ public class LongestSubstringWithAtMostKDistinctCharacters {
11
11
/**
12
12
* 思路跟Longest Substring With At Most Two Distinct Characters一样,只是给2改成k,要注意k等于0时返回0
13
13
*/
14
- // 耗时9ms
15
14
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
+ }
31
24
}
32
25
}
33
-
34
26
longest = Math .max (longest , j - i + 1 );
35
27
}
36
-
37
28
return longest ;
38
29
}
39
30
Original file line number Diff line number Diff line change @@ -30,27 +30,20 @@ public static void main(String[] args) {
30
30
test .call ("how" );
31
31
}
32
32
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
+ }
48
44
}
45
+ longest = Math .max (longest , j - i + 1 );
49
46
}
50
- List <Integer > list = new LinkedList <>();
51
- while (!queue .isEmpty ()) {
52
- list .add (queue .poll ());
53
- }
54
- return list ;
47
+ return longest ;
55
48
}
56
49
}
You can’t perform that action at this time.
0 commit comments