Skip to content

Commit f38e2c2

Browse files
add a solution for 340
1 parent 4dd42b4 commit f38e2c2

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

src/main/java/com/fishercoder/solutions/_340.java

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ public int lengthOfLongestSubstringKDistinct(String s, int k) {
2121
if (num > k) {
2222
while (--count[s.charAt(left++)] > 0) {
2323
}
24-
;
2524
num--;
2625
}
2726
result = Math.max(result, right - left + 1);
@@ -57,4 +56,35 @@ public int lengthOfLongestSubstringKDistinct(String s, int k) {
5756
}
5857
}
5958

59+
public static class Solution3 {
60+
/**
61+
* My original solution on 10/20/2021, a very generic sliding window template.
62+
*/
63+
public int lengthOfLongestSubstringKDistinct(String s, int k) {
64+
int left = 0;
65+
int right = 0;
66+
int ans = 0;
67+
int[] count = new int[256];
68+
int distinctCount = 0;
69+
while (right < s.length()) {
70+
if (count[s.charAt(right)] == 0) {
71+
distinctCount++;
72+
}
73+
count[s.charAt(right)]++;
74+
right++;
75+
if (distinctCount <= k) {
76+
ans = Math.max(ans, right - left);
77+
}
78+
while (distinctCount > k) {
79+
count[s.charAt(left)]--;
80+
if (count[s.charAt(left)] == 0) {
81+
distinctCount--;
82+
}
83+
left++;
84+
}
85+
}
86+
return ans;
87+
}
88+
}
89+
6090
}

src/test/java/com/fishercoder/_340Test.java

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,26 @@
99
public class _340Test {
1010
private static _340.Solution1 solution1;
1111
private static _340.Solution2 solution2;
12+
private static _340.Solution3 solution3;
13+
private static String s;
14+
private static int k;
15+
private static int expected;
1216

1317
@BeforeClass
1418
public static void setup() {
1519
solution1 = new _340.Solution1();
1620
solution2 = new _340.Solution2();
21+
solution3 = new _340.Solution3();
1722
}
1823

1924
@Test
2025
public void test1() {
21-
assertEquals(3, solution1.lengthOfLongestSubstringKDistinct("eceba", 2));
22-
assertEquals(3, solution2.lengthOfLongestSubstringKDistinct("eceba", 2));
26+
s = "eceba";
27+
k = 2;
28+
expected = 3;
29+
assertEquals(expected, solution1.lengthOfLongestSubstringKDistinct(s, k));
30+
assertEquals(expected, solution2.lengthOfLongestSubstringKDistinct(s, k));
31+
assertEquals(expected, solution3.lengthOfLongestSubstringKDistinct(s, k));
2332
}
2433

2534
@Test

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy