forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[DP] Add a solution to Palindromic Substrings
- Loading branch information
Showing
2 changed files
with
49 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 | ||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters