647-palindromic-substrings¶
Try it on leetcode
Description¶
Given a string s
, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Constraints:
1 <= s.length <= 1000
s
consists of lowercase English letters.
Solution(Python)¶
class Solution:
def countSubstrings(self, s: str) -> int:
return self.dptable(s)
# Time Complexity: O(n^3)
# Space Complexity: O(1)
def bruteforce(self, s: str) -> int:
n = len(s)
cnt = 0
for i in range(n):
for j in range(i, n):
if self.ispalindrome(s[i: j + 1]):
cnt += 1
return cnt
# Time Complexity: O(n^2)
# Space Complexity: O(n^2)
def topdown(self, s: str) -> int:
n = len(s)
cnt = 0
dp = [[-1 for _ in range(n)] for _ in range(n)]
def solve(i, j):
if i >= j:
return 1
if dp[i][j] != -1:
return dp[i][j]
dp[i][j] = solve(i + 1, j - 1) if s[i] == s[j] else 0
return dp[i][j]
for i in range(n):
for j in range(i, n):
cnt += solve(i, j)
return cnt
# Time Complexity: O(n^2)
# Space Complexity: O(n^2)
def dptable(self, s: str) -> int:
n = len(s)
dp = [[False] * n for _ in range(n)]
ans = 0
for i in range(n - 1, -1, -1):
for j in range(i, n):
if s[i] == s[j]:
if i + 1 >= j:
dp[i][j] = True
else:
dp[i][j] = dp[i + 1][j - 1]
if dp[i][j]:
ans += 1
return ans
def ispalindrome(self, string):
s, e = 0, len(string) - 1
while s <= e:
if string[s] != string[e]:
return False
s += 1
e -= 1
return True