File tree 1 file changed +30
-0
lines changed
longest-palindromic-substring
1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def is_palindrome (self , s : str ) -> bool :
3
+ return s == s [::- 1 ]
4
+
5
+ def longestPalindrome (self , s : str ) -> str :
6
+ """
7
+ - Idea: ์๋์ ๋ฐฉ๋ฒ์ผ๋ก ์ฃผ์ด์ง ๋ฌธ์์ด์์ ๊ฐ์ฅ ๊ธด ํฐ๋ฆฐ๋๋กฌ์ ์ฐพ๋๋ค.
8
+ 1. ๋ชจ๋ ๊ฐ๋ฅํ ๋ถ๋ถ ๋ฌธ์์ด ์์ฑ
9
+ 2. ๊ฐ ๋ถ๋ถ ๋ฌธ์์ด์ด ํฐ๋ฆฐ๋๋กฌ์ธ์ง ํ์ธ
10
+ 3. ๊ฐ์ฅ ๊ธด ํฐ๋ฆฐ๋๋กฌ์ ์ ์ฅํ๊ณ ๋ฐํ
11
+ - Time Complexity: O(n^3). n์ ๋ฌธ์์ด์ ๊ธธ์ด
12
+ ๋ชจ๋ ๋ถ๋ถ ๋ฌธ์์ด์ ๊ตฌํ๋๋ฐ O(n^2), ๊ฐ ๋ถ๋ถ ๋ฌธ์์ด์ด ํฐ๋ฆฐ๋๋กฌ์ธ์ง ์์๋ด๋๋ฐ O(n).
13
+ ๊ฒฐ๊ตญ O(n^3)์ ์๊ฐ์ด ์์๋๋ค.
14
+ - Space Complexity: O(n). n์ ๋ฌธ์์ด์ ๊ธธ์ด
15
+ ํฐ๋ฆฐ๋๋กฌ์ธ์ง ํ์ธํ ๋ ๋ฌธ์์ด ์ฌ๋ผ์ด์ฑ์ ์ฌ์ฉํ๋๋ฐ,
16
+ ์ต์
์ ๊ฒฝ์ฐ ๋ถ๋ถ ๋ฌธ์์ด์ ๊ธธ์ด๊ฐ ์
๋ ฅ ๋ฌธ์์ด์ ๊ธธ์ด์ ๊ฐ์
17
+ ๊ณต๊ฐ ๋ณต์ก๋๋ O(n)์ด๋ค.
18
+ """
19
+
20
+ result = s [0 ]
21
+
22
+ for i in range (len (s ) - 1 ):
23
+ for j in range (i + 1 , len (s ) + 1 ):
24
+ if j - i <= len (result ):
25
+ continue
26
+
27
+ if self .is_palindrome (s [i :j ]) and (j - i ) > len (result ):
28
+ result = s [i :j ]
29
+
30
+ return result
You canโt perform that action at this time.
0 commit comments