File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ package Review_2024 ;
2+
3+ import java .util .Map ;
4+ import java .util .HashMap ;
5+
6+ public class LongestSubstringWKDistinctChars {
7+
8+ public int longestSubstringWKDistinctChars (String s , int k ) {
9+ if (s == null || s .length () == 0 || k == 0 ) {
10+ return 0 ;
11+ }
12+
13+ Map <Character , Integer > charMap = new HashMap <>();
14+ int left = 0 ;
15+ int maxLen = 0 ;
16+
17+ for (int right = 0 ; right < s .length (); right ++) {
18+ char c = s .charAt (right );
19+ charMap .put (c , right );
20+
21+ while (charMap .size () > k ) {
22+ char lc = s .charAt (left );
23+ if (charMap .get (lc ) == left ) {
24+ charMap .remove (lc );
25+ }
26+ left ++;
27+ }
28+ maxLen = Math .max (maxLen , right - left + 1 );
29+ }
30+ return maxLen ;
31+ }
32+
33+ public static void main (String [] args ) {
34+ LongestSubstringWKDistinctChars ls = new LongestSubstringWKDistinctChars ();
35+ String s = "eceba" ;
36+ int k = 2 ;
37+ int len = ls .longestSubstringWKDistinctChars (s , k );
38+ System .out .println (len );
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments