File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ *
3+ * ์ ๊ทผ ๋ฐฉ๋ฒ :
4+ * - ํฐ๋ฆฐ๋๋กฌ์ ์ข์ฐ ๋์นญ ๋ฌธ์์ด์ ์ฐพ์์ผ ํ๋ค.
5+ * - ๋ฌธ์์ด ์ค์ฌ์ด 1๊ฐ(ํ์)์ผ ๋์ 2๊ฐ(์ง์)์ผ ๋ ๊ณ ๋ คํด์ ํฐ๋ฆฐ๋๋กฌ์ ํ์ฅํ๋ฉฐ ๊ธด ๋ฌธ์์ด์ ๋ฆฌํดํ๋ค.
6+ *
7+ * ์๊ฐ๋ณต์ก๋ : O(n^2)
8+ * - n = s ๋ฌธ์์ด ๊ธธ์ด
9+ * - ๋์ผ ๋ฌธ์์ธ ๊ฒฝ์ฐ for๋ฌธ๊ณผ while๋ฌธ์์ 2๋ฒ ์ํ ๋ฐ์ O(n)
10+ *
11+ * ๊ณต๊ฐ๋ณต์ก๋ : O(1)
12+ * - ๊ณ ์ ๋ ๋ณ์๋ง ์ฌ์ฉ
13+ *
14+ */
15+ function longestPalindrome ( s : string ) : string {
16+ let result = "" ;
17+
18+ function expandFromCenter ( start : number , end : number ) {
19+ while ( start >= 0 && end < s . length && s [ start ] === s [ end ] ) {
20+ start -- ;
21+ end ++ ;
22+ }
23+ return s . slice ( start + 1 , end ) ;
24+ }
25+
26+ for ( let i = 0 ; i < s . length ; i ++ ) {
27+ const oddPalindrome = expandFromCenter ( i , i ) ;
28+ if ( oddPalindrome . length > result . length ) result = oddPalindrome ;
29+
30+ const evenPalindrome = expandFromCenter ( i , i + 1 ) ;
31+ if ( evenPalindrome . length > result . length ) result = evenPalindrome ;
32+ }
33+
34+ return result ;
35+ }
You canโt perform that action at this time.
0 commit comments