|
| 1 | +/* |
| 2 | +647. Palindromic Substrings |
| 3 | +
|
| 4 | +Example 1: |
| 5 | +Input: s = "abc" |
| 6 | +Output: 3 |
| 7 | +Explanation: Three palindromic strings: "a", "b", "c". |
| 8 | +
|
| 9 | +Example 2: |
| 10 | +Input: s = "aaa" |
| 11 | +Output: 6 |
| 12 | +Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". |
| 13 | + */ |
| 14 | + |
| 15 | +// Time complexity: O(n^3) |
| 16 | +// Space complexity: O(n^3) |
| 17 | +function countSubstrings(s: string): number { |
| 18 | + function isPalindrome(s: string): boolean { |
| 19 | + if (s.length === 0) return false; |
| 20 | + if (s.length === 1) return true; |
| 21 | + let left = 0; |
| 22 | + let right = s.length - 1; |
| 23 | + while (left < right) { |
| 24 | + if (s[left] !== s[right]) return false; |
| 25 | + left++; |
| 26 | + right--; |
| 27 | + } |
| 28 | + return true; |
| 29 | + } |
| 30 | + |
| 31 | + const candidates = new Map<string, number>(); |
| 32 | + for (let i = 0; i < s.length; i++) { |
| 33 | + for (let j = i + 1; j <= s.length; j++) { |
| 34 | + // this will cost both t.c. and s.c. O(n^3) |
| 35 | + candidates.set(s.slice(i, j), (candidates.get(s.slice(i, j)) || 0) + 1); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + let count = 0; |
| 40 | + for (const [key, value] of candidates) { |
| 41 | + if (isPalindrome(key)) count += value |
| 42 | + } |
| 43 | + |
| 44 | + return count; |
| 45 | +}; |
| 46 | + |
| 47 | +// Time complexity: O(n^3) |
| 48 | +// Space complexity: O(1) |
| 49 | +function countSubstrings(s: string): number { |
| 50 | + function isPalindrome(s: string): boolean { |
| 51 | + if (s.length === 0) return false; |
| 52 | + if (s.length === 1) return true; |
| 53 | + let left = 0; |
| 54 | + let right = s.length - 1; |
| 55 | + while (left < right) { |
| 56 | + if (s[left] !== s[right]) return false; |
| 57 | + left++; |
| 58 | + right--; |
| 59 | + } |
| 60 | + return true; |
| 61 | + } |
| 62 | + |
| 63 | + let count = 0; |
| 64 | + for (let i = 0; i < s.length; i++) { |
| 65 | + for (let j = i + 1; j <= s.length; j++) { |
| 66 | + // this will cause t.c. O(n^3). need to optimize this part |
| 67 | + if (isPalindrome(s.slice(i, j))) count++; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return count; |
| 72 | +} |
| 73 | + |
| 74 | +// Time complexity: O(n^2) |
| 75 | +// Space complexity: O(1) |
| 76 | +function countSubstrings(s: string): number { |
| 77 | + function expandIsPalindrome(left: number, right: number): number { |
| 78 | + let count = 0; |
| 79 | + while (left >= 0 && right < s.length && s[left] === s[right]) { |
| 80 | + count++; |
| 81 | + left--; |
| 82 | + right++; |
| 83 | + } |
| 84 | + return count; |
| 85 | + } |
| 86 | + |
| 87 | + let count = 0; |
| 88 | + for (let i = 0; i < s.length; i++) { |
| 89 | + count += expandIsPalindrome(i, i); |
| 90 | + count += expandIsPalindrome(i, i + 1); |
| 91 | + } |
| 92 | + return count; |
| 93 | +} |
0 commit comments