|
| 1 | +''' |
| 2 | +# 647. Palindromic Substrings |
| 3 | +
|
| 4 | +A. use dynamic programming table to store the palindrome status. |
| 5 | +B. use two pointers to expand around the center. |
| 6 | +
|
| 7 | +## Time and Space Complexity |
| 8 | +
|
| 9 | +### A. Dynamic Programming Table |
| 10 | +``` |
| 11 | +TC: O(n^2) |
| 12 | +SC: O(n^2) |
| 13 | +``` |
| 14 | +
|
| 15 | +#### TC is O(n^2): |
| 16 | +- filling DP table by iterating through all substrings. |
| 17 | +- each cell (i, j) checks if a substring is a palindrome & counting the cases = O(n^2) |
| 18 | +
|
| 19 | +#### SC is O(n^2): |
| 20 | +- storing the n x n dp table. = O(n^2) |
| 21 | +
|
| 22 | +### B. Expand Around Center |
| 23 | +``` |
| 24 | +TC: O(n^2) |
| 25 | +SC: O(1) |
| 26 | +``` |
| 27 | +
|
| 28 | +#### TC is O(n^2): |
| 29 | +- for each char, expand outwards to check for palindromes. = O(n^2) |
| 30 | +
|
| 31 | +#### SC is O(1): |
| 32 | +- no additional data structures are used. `count` is a single integer. = O(1) |
| 33 | +''' |
| 34 | +class Solution: |
| 35 | + def countSubstringsDPTable(self, s: str) -> int: |
| 36 | + ''' |
| 37 | + A. Dynamic Programming Table |
| 38 | + ''' |
| 39 | + n = len(s) |
| 40 | + dp = [[False] * n for _ in range(n)] # List comprehension. = SC: O(n^2) |
| 41 | + count = 0 |
| 42 | + |
| 43 | + for i in range(n): # TC: O(n) |
| 44 | + dp[i][i] = True |
| 45 | + count += 1 |
| 46 | + |
| 47 | + for i in range(n - 1): |
| 48 | + if s[i] == s[i + 1]: |
| 49 | + dp[i][i + 1] = True |
| 50 | + count += 1 |
| 51 | + |
| 52 | + for s_len in range(3, n + 1): # TC: O(n) |
| 53 | + for i in range(n - s_len + 1): # TC: O(n) |
| 54 | + j = i + s_len - 1 |
| 55 | + |
| 56 | + if s[i] == s[j] and dp[i + 1][j - 1]: |
| 57 | + dp[i][j] = True |
| 58 | + count += 1 |
| 59 | + |
| 60 | + return count |
| 61 | + def countSubstrings(self, s: str) -> int: |
| 62 | + ''' |
| 63 | + B. Expand Around Center |
| 64 | + ''' |
| 65 | + count = 0 |
| 66 | + |
| 67 | + def expand(left, right): |
| 68 | + nonlocal count |
| 69 | + while left >= 0 and right < len(s) and s[left] == s[right]: # TC: O(n) |
| 70 | + count += 1 |
| 71 | + left -= 1 |
| 72 | + right += 1 |
| 73 | + |
| 74 | + for i in range(len(s)): # TC: O(n) |
| 75 | + expand(i, i) |
| 76 | + expand(i, i + 1) |
| 77 | + |
| 78 | + return count |
0 commit comments