File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string } s
3+ * @return {string }
4+ */
5+ const longestPalindrome = function ( s ) {
6+ let substr = '' ;
7+
8+ for ( let i = 0 ; i < s . length ; i ++ ) {
9+ const oddStr = getCurrentLongestPalindrome ( i , i ) ; // s[i] ๊ธฐ์ค ์์์ผ๋ก ๋ป์ด๋๊ฐ => length๋ ํญ์ ํ์
10+ const evenStr = getCurrentLongestPalindrome ( i , i + 1 ) ; // s[i] + s[i+1] ๊ธฐ์ค ์์์ผ๋ก => length๋ ํญ์ ์ง์
11+
12+ if ( substr . length < oddStr . length ) substr = oddStr ;
13+ if ( substr . length < evenStr . length ) substr = evenStr ;
14+ }
15+
16+ // ๊ธฐ์ค ๋ฌธ์์ด์ ํฌํจํ๋ฉด์ ๊ฐ์ฅ ๊ธด ํฐ๋ฆฐ๋๋กฌ์ ์ฐพ์ ๋ฐํํ๋ ํจ์ (๊ธฐ์ค ๋ฌธ์์ด: s.slice(l, r + 1))
17+ const getCurrentLongestPalindrome = function ( l , r ) {
18+ while ( 0 <= l && r < s . length && s [ l ] === s [ r ] ) {
19+ l -- ;
20+ r ++ ;
21+ }
22+
23+ return s . slice ( l + 1 , r ) ;
24+ }
25+
26+ return substr ;
27+ } ;
28+
29+ // ์๊ฐ๋ณต์ก๋: O(n^2)
30+ // ๊ณต๊ฐ๋ณต์ก๋: O(s) (s: substr.length)
You canโt perform that action at this time.
0 commit comments