forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestPalindromicSubstring.swift
38 lines (31 loc) · 1.06 KB
/
LongestPalindromicSubstring.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Question Link: https://leetcode.com/problems/longest-palindromic-substring/
* Primary idea: Find the longest palindrome string from every index at the center.
* Time Complexity: O(n^2), Space Complexity: O(1)
*
*/
class LongestPalindromicSubstring {
func longestPalindrome(_ s: String) -> String {
guard s.count > 1 else {
return s
}
let sChars = Array(s)
var maxLen = 0, start = 0
for i in 0..<sChars.count {
searchPalindrome(sChars, i, i, &start, &maxLen)
searchPalindrome(sChars, i, i + 1, &start, &maxLen)
}
return String(sChars[start..<start + maxLen])
}
private func searchPalindrome(_ chars: [Character], _ l: Int, _ r: Int, _ start: inout Int, _ maxLen: inout Int) {
var l = l, r = r
while l >= 0 && r < chars.count && chars[l] == chars[r] {
l -= 1
r += 1
}
if maxLen < r - l - 1 {
start = l + 1
maxLen = r - l - 1
}
}
}