File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
longest-substring-without-repeating-characters Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
3+ * @param {string } s
4+ * @return {number }
5+ */
6+ var lengthOfLongestSubstring = function ( s ) {
7+ let longestS = [ ] ;
8+ let result = 0 ;
9+ for ( let char of s ) {
10+ if ( ! longestS . includes ( char ) ) {
11+ longestS . push ( char ) ;
12+ } else {
13+ result = Math . max ( result , longestS . length ) ;
14+ longestS = longestS . slice ( longestS . indexOf ( char ) + 1 ) ;
15+ longestS . push ( char ) ;
16+ }
17+ }
18+ return Math . max ( result , longestS . length ) ;
19+ } ;
20+
21+ /*
22+ Sliding Window
23+ Sliding Window๋ ๋ฌธ์์ด์ด๋ ๋ฐฐ์ด์์ ์ฐ์๋ ๋ถ๋ถ(subarray/substring)์ ๋ค๋ฃฐ ๋ ์์ฃผ ์ ์ฉํ ์๊ณ ๋ฆฌ์ฆ ๊ธฐ๋ฒ
24+ ๊ณ ์ ๋๊ฑฐ๋ ์ ๋์ ์ธ โ์ฐฝ(window)โ์ ์ข์ฐ๋ก ์์ง์ด๋ฉฐ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๋ฐฉ์
25+
26+ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ ํต์ฌ ์์ด๋์ด
27+ 1. ๋ ํฌ์ธํฐ ์ฌ์ฉ: left, right
28+ 2. ์กฐ๊ฑด์ ๋ง์กฑํ๋ ์๋์ฐ ์ ์ง
29+ 3. ์กฐ๊ฑด์ด ๊นจ์ง๋ฉด left๋ฅผ ์ด๋
30+ 4. ์กฐ๊ฑด์ ๋ง์กฑํ๋ฉด ๊ฒฐ๊ณผ ์
๋ฐ์ดํธ
31+ */
32+ var lengthOfLongestSubstring = function ( s ) {
33+ let set = new Set ( ) ;
34+ let left = 0 ;
35+ let maxLen = 0 ;
36+
37+ for ( let right = 0 ; right < s . length ; right ++ ) {
38+ while ( set . has ( s [ right ] ) ) {
39+ set . delete ( s [ left ] ) ; // ์ค๋ณต ๋ฌธ์ ์ ๊ฑฐ
40+ left ++ ; // ์ผ์ชฝ ํฌ์ธํฐ ์ด๋
41+ }
42+ set . add ( s [ right ] ) ; // ํ์ฌ ๋ฌธ์ ์ถ๊ฐ
43+ maxLen = Math . max ( maxLen , right - left + 1 ) ; // ์ต๋ ๊ธธ์ด ์
๋ฐ์ดํธ
44+ }
45+
46+ return maxLen ;
47+ } ;
You canโt perform that action at this time.
0 commit comments