Skip to content

Commit

Permalink
[DP] Refactor the solution to Longest Palindromic Substring
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu authored Sep 11, 2019
1 parent 6e963ad commit 45f3b33
Showing 1 changed file with 19 additions and 30 deletions.
49 changes: 19 additions & 30 deletions DP/LongestPalindromicSubstring.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
/**
* Question Link: https://leetcode.com/problems/longest-palindromic-substring/
* Primary idea: 2D Dynamic Programming, update boolean array based on
* current two characters' equity and the previous boolean subarray
* Time Complexity: O(n^2), Space Complexity: O(n^2)
* Primary idea: Find the longest palindrome string from every index at the center.
* Time Complexity: O(n^2), Space Complexity: O(1)
*
*/

Expand All @@ -12,38 +11,28 @@ class LongestPalindromicSubstring {
return s
}

var sChars = Array(s)
let len = sChars.count
var maxLen = 1
var maxStart = 0
var isPalin = Array(repeating: Array(repeating: false, count : len), count : len)
let sChars = Array(s)
var maxLen = 0, start = 0

// set palindrome whose len is 1
for i in 0...len - 1 {
isPalin[i][i] = true
for i in 0..<sChars.count {
searchPalindrome(sChars, i, i, &start, &maxLen)
searchPalindrome(sChars, i, i + 1, &start, &maxLen)
}

// set palindrome whose len is 2
for i in 0...len - 2 {
if sChars[i] == sChars[i + 1] {
isPalin[i][i + 1] = true
maxLen = 2
maxStart = i
}
}
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

if len >= 3 {
for length in 3...len {
for i in 0...len - length {
if sChars[i] == sChars[i + length - 1] && isPalin[i + 1][i + length - 2] {
isPalin[i][i + length - 1] = true
maxLen = length
maxStart = i
}
}
}
while l >= 0 && r < chars.count && chars[l] == chars[r] {
l -= 1
r += 1
}

return String(sChars[maxStart...maxStart + maxLen - 1])
if maxLen < r - l - 1 {
start = l + 1
maxLen = r - l - 1
}
}
}

0 comments on commit 45f3b33

Please sign in to comment.