File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
longest-substring-without-repeating-characters Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/longest-substring-without-repeating-characters/
3+ * time complexity : O(n)
4+ * space complexity : O(n)
5+ */
6+ function lengthOfLongestSubstring ( s : string ) : number {
7+ let n = s . length , ans = 0 ;
8+ const map = new Map < string , number > ( ) ;
9+ for ( let j = 0 , i = 0 ; j < n ; j ++ ) {
10+ if ( map . has ( s [ j ] ) ) {
11+ i = Math . max ( ( map . get ( s [ j ] ) ?? 0 ) + 1 , i ) ;
12+ }
13+ ans = Math . max ( ans , j - i + 1 ) ;
14+ map . set ( s [ j ] , j ) ;
15+ }
16+ console . log ( 'map:' , map ) ;
17+ return ans ;
18+ } ;
19+
20+ const testInput1 = "abcabcbb" ;
21+ const testInput2 = "bbbbb" ;
22+ const testInput3 = "pwwkew" ;
23+
24+ console . log ( 'output1:' , lengthOfLongestSubstring ( testInput1 ) , 'expected:' , 3 ) ;
25+ console . log ( 'output2:' , lengthOfLongestSubstring ( testInput2 ) , 'expected:' , 1 ) ;
26+ console . log ( 'output3:' , lengthOfLongestSubstring ( testInput3 ) , 'expected:' , 3 ) ;
You can’t perform that action at this time.
0 commit comments