File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
longest-substring-without-repeating-characters Expand file tree Collapse file tree 1 file changed +65
-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+ * T.C. O(n^2)
4+ * S.C. O(n)
5+ */
6+ // function lengthOfLongestSubstring(s: string): number {
7+ // let max = 0;
8+ // for (let i = 0; i < s.length; i++) {
9+ // const SET = new Set();
10+ // let count = 0;
11+ // for (let j = i; j < s.length; j++) {
12+ // if (SET.has(s[j])) break;
13+ // SET.add(s[j]);
14+ // count += 1;
15+ // max = Math.max(max, count);
16+ // }
17+ // }
18+ // return max;
19+ // }
20+
21+ /**
22+ * T.C. O(n)
23+ * S.C. O(n)
24+ */
25+ // function lengthOfLongestSubstring(s: string): number {
26+ // let left = 0;
27+ // let right = 0;
28+ // let max = 0;
29+ // const SET = new Set();
30+
31+ // while (s[right]) {
32+ // if (SET.has(s[right])) {
33+ // SET.delete(s[left]);
34+ // left++;
35+ // } else {
36+ // SET.add(s[right]);
37+ // max = Math.max(SET.size, max);
38+ // right++;
39+ // }
40+ // }
41+
42+ // return max;
43+ // }
44+
45+ /**
46+ * T.C. O(n)
47+ * S.C. O(n)
48+ */
49+ function lengthOfLongestSubstring ( s : string ) : number {
50+ let left = 0 ;
51+ let right = 0 ;
52+ let max = 0 ;
53+ const MAP = new Map < string , number > ( ) ;
54+
55+ while ( right < s . length ) {
56+ if ( MAP . has ( s [ right ] ) ) {
57+ left = Math . max ( MAP . get ( s [ right ] ) ! + 1 , left ) ;
58+ }
59+ MAP . set ( s [ right ] , right ) ;
60+ max = Math . max ( max , right - left + 1 ) ;
61+ right ++ ;
62+ }
63+
64+ return max ;
65+ }
You can’t perform that action at this time.
0 commit comments