forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindromicSubstrings.swift
47 lines (39 loc) · 1.3 KB
/
PalindromicSubstrings.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
39
40
41
42
43
44
45
46
47
/**
* Question Link: https://leetcode.com/problems/palindromic-substrings/
* 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)
*
*/
class PalindromicSubstrings {
func countSubstrings(_ s: String) -> Int {
var palinCount = 0, dp = Array(repeating: Array(repeating: false, count: s.count), count: s.count)
var s = Array(s)
// init case with distance of 0 and 1
for i in 0..<s.count {
dp[i][i] = true
palinCount += 1
}
guard s.count > 1 else {
return palinCount
}
for i in 0..<s.count - 1 {
if s[i] == s[i + 1] {
dp[i][i + 1] = true
palinCount += 1
}
}
guard s.count > 2 else {
return palinCount
}
for distance in 2...s.count - 1 {
for i in 0..<s.count - distance {
if s[i] == s[i + distance] && dp[i + 1][i + distance - 1] {
dp[i][i + distance] = true
palinCount += 1
}
}
}
return palinCount
}
}