File tree 2 files changed +49
-0
lines changed
javascript/algorithms/strings
2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Sliding window: TC: O(n), SC: O(n)
2
+ package java1 .algorithms .strings ;
3
+
4
+ import java .util .HashSet ;
5
+
6
+ public class longestSubstringWithoutRepeatingChar {
7
+ private static int longestSubstringLengthWithoutRepeatingChar (String str ) {
8
+ HashSet <Character > hashset = new HashSet <>();
9
+ int left = 0 , max = 0 ;
10
+
11
+ for (int right = 0 ; right < str .length (); right ++) {
12
+ while (hashset .contains (str .charAt (right ))){
13
+ hashset .remove (str .charAt (left ));
14
+ left ++;
15
+ }
16
+ hashset .add (str .charAt (right ));
17
+ max = Math .max (max , hashset .size ());
18
+ }
19
+ return max ;
20
+ }
21
+
22
+ public static void main (String [] args ) {
23
+ String string1 = "abcabcbbaa" ;
24
+ System .out .println (longestSubstringLengthWithoutRepeatingChar (string1 ));
25
+ String string2 = "aaaaaaa" ;
26
+ System .out .println (longestSubstringLengthWithoutRepeatingChar (string2 ));
27
+ }
28
+
29
+ }
Original file line number Diff line number Diff line change
1
+ // Sliding window: TC: O(n), SC: O(n)
2
+ function longestSubstringLengthWithoutRepeatingChar ( string ) {
3
+ let set = new Set ( ) ;
4
+ let left = max = 0 ;
5
+
6
+ for ( let right = 0 ; right < string . length ; right ++ ) {
7
+ while ( set . has ( string [ right ] ) ) {
8
+ set . delete ( string [ left ] ) ;
9
+ left ++ ;
10
+ }
11
+ set . add ( string [ right ] ) ;
12
+ max = Math . max ( max , set . size ) ;
13
+ }
14
+ return max ;
15
+ }
16
+
17
+ let string1 = "abcabcbbaa" ;
18
+ console . log ( longestSubstringLengthWithoutRepeatingChar ( string1 ) ) ;
19
+ let string2 = "aaaaaaa" ;
20
+ console . log ( longestSubstringLengthWithoutRepeatingChar ( string2 ) ) ;
You can’t perform that action at this time.
0 commit comments