File tree 1 file changed +39
-0
lines changed
longest-palindromic-substring
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ //
2
+ // 5. Longest Palindromic Substring
3
+ // https://leetcode.com/problems/longest-palindromic-substring/description/
4
+ // Dale-Study
5
+ //
6
+ // Created by WhiteHyun on 2024/07/06.
7
+ //
8
+
9
+ class Solution {
10
+ func longestPalindrome( _ s: String ) -> String {
11
+ let array = Array ( s)
12
+ if array. count == 1 { return s }
13
+
14
+ var start = 0
15
+ var maxLength = 1
16
+
17
+ func expandAroundCenter( _ left: Int , _ right: Int ) -> Int {
18
+ var l = left
19
+ var r = right
20
+ while l >= 0 , r < array. count, array [ l] == array [ r] {
21
+ l -= 1
22
+ r += 1
23
+ }
24
+ return r - l - 1
25
+ }
26
+
27
+ for index in array. indices {
28
+ let length1 = expandAroundCenter ( index, index) // 홀수 길이
29
+ let length2 = expandAroundCenter ( index, index + 1 ) // 짝수 길이
30
+ let length = max ( length1, length2)
31
+
32
+ if length > maxLength {
33
+ start = index - ( length - 1 ) / 2
34
+ maxLength = length
35
+ }
36
+ }
37
+ return String ( array [ start ..< start + maxLength] )
38
+ }
39
+ }
You can’t perform that action at this time.
0 commit comments