File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ https://leetcode.com/problems/longest-palindromic-substring/
3
+
4
+ ๋ฌธ์์ด s๊ฐ ์ฃผ์ด์ก์ ๋, ๊ฐ์ฅ ๊ธด ํฐ๋ฆฐ๋๋กฌ ๋ถ๋ถ ๋ฌธ์์ด์ ์ฐพ์์ ๋ฐํํ๋ ํจ์๋ฅผ ์์ฑํด๋ผ.
5
+
6
+ ๋ฌธ์ ํ์ด
7
+
8
+ 1. ๋ฌธ์์ด `s`์ ๋ชจ๋ ์ธ๋ฑ์ค `i`๋ฅผ ๊ธฐ์ค์ผ๋ก,
9
+ 2. ๋ ์ข
๋ฅ์ ์ค์ฌ์์ ํฐ๋ฆฐ๋๋กฌ์ ํ์ฅํด ๋ณธ๋ค:
10
+ - ํ์ ๊ธธ์ด: `s[i]`๋ฅผ ์ค์ฌ์ผ๋ก ์ข์ฐ ํ์ฅ (`i, i`)
11
+ - ์ง์ ๊ธธ์ด: `s[i]`์ `s[i+1]`์ ์ค์ฌ์ผ๋ก ์ข์ฐ ํ์ฅ (`i, i+1`)
12
+ 3. ๊ฐ ์ค์ฌ์์ while๋ฌธ์ผ๋ก `s[left] == s[right]`์ธ ๋์ ํ์ฅ
13
+ 4. ๊ฐ์ฅ ๊ธด ํฐ๋ฆฐ๋๋กฌ ๋ฌธ์์ด์ ๊ณ์ ์
๋ฐ์ดํธ
14
+ 5. ์ต์ข
์ ์ผ๋ก ๊ฐ์ฅ ๊ธด ํฐ๋ฆฐ๋๋กฌ์ ๋ฐํํ๋ค
15
+
16
+ TC: O(n^2)
17
+ SC: O(1)
18
+ """
19
+
20
+
21
+ class Solution :
22
+ def longestPalindrome (self , s : str ) -> str :
23
+ def expand (left : int , right : int ) -> str :
24
+ while left >= 0 and right < len (s ) and s [left ] == s [right ]:
25
+ left -= 1
26
+ right += 1
27
+
28
+ return s [left + 1 : right ]
29
+
30
+ res = ""
31
+ for i in range (len (s )):
32
+ temp1 = expand (i , i ) # ํ์ ๊ธธ์ด ํฐ๋ฆฐ๋๋กฌ
33
+ temp2 = expand (i , i + 1 ) # ์ง์ ๊ธธ์ด ํฐ๋ฆฐ๋๋กฌ
34
+ if len (temp1 ) > len (res ):
35
+ res = temp1
36
+ if len (temp2 ) > len (res ):
37
+ res = temp2
38
+ return res
You canโt perform that action at this time.
0 commit comments