File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/longest-palindromic-substring/submissions/1694755721/
3
+ * @param {string } s
4
+ * @return {string }
5
+ */
6
+ var longestPalindrome = function ( s ) {
7
+ // 결과로 반환할 가장 긴 팰린드롬 초기값
8
+ let result = '' ;
9
+
10
+ // 팰린드롬의 중심에서 양쪽으로 확장하는 함수
11
+ function expandAroundCenter ( left , right ) {
12
+ // 왼쪽이 0 이상, 오른쪽이 문자열 길이 이하이며
13
+ // 양쪽 문자가 같으면 계속 확장
14
+ while ( left >= 0 && right < s . length && s [ left ] === s [ right ] ) {
15
+ left -- ;
16
+ right ++ ;
17
+ }
18
+ // while문을 빠져나오면 팰린드롬이 아님.
19
+ // 현재 찾은 팰린드롬 반환
20
+ return s . slice ( left + 1 , right ) ;
21
+ }
22
+
23
+ // 문자열의 각 문자를 중심으로 확장 시도
24
+ for ( let i = 0 ; i < s . length ; i ++ ) {
25
+ // 홀수 길이 팰린드롬 (중심이 한 글자)
26
+ const oddPalindrome = expandAroundCenter ( i , i ) ;
27
+ // 짝수 길이 팰린드롬 (중심이 두 글자)
28
+ const evenPalindrome = expandAroundCenter ( i , i + 1 ) ;
29
+
30
+ // 더 긴 팰린드롬 선택
31
+ if ( oddPalindrome . length > result . length ) {
32
+ result = oddPalindrome ;
33
+ }
34
+ if ( evenPalindrome . length > result . length ) {
35
+ result = evenPalindrome ;
36
+ }
37
+ }
38
+
39
+ // 결과 반환
40
+ return result ;
41
+ } ;
You can’t perform that action at this time.
0 commit comments