Skip to content

Commit

Permalink
5: palindromic-substrings
Browse files Browse the repository at this point in the history
  • Loading branch information
whewchews committed Aug 17, 2024
1 parent 718bde0 commit 34a18cd
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions palindromic-substrings/whewchews.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
function countSubstrings(s: string): number {
// SC: O(N^2)
const dict: Map<string, boolean> = new Map();
const n = s.length;

// TC: O(N^2)
for (let start = 0; start < n; start++) {
for (let end = start; end >= 0; end--) {
if (start === end) {
dict.set(`${start}:${end}`, true);
} else if (start + 1 === end) {
dict.set(`${start}:${end}`, s[start] === s[end]);
} else {
const flag = s[start] === s[end];
const mid = dict.get(`${start + 1}:${end - 1}`);
dict.set(`${start}:${end}`, flag && mid);
}
}
}

let cnt = 0;

// TC: O(N^2)
// SC: O(1)
for (const v of dict.values()) {
if (v) {
cnt++;
}
}

return cnt;
}

// TC: O(N^2)
// SC: O(N^2)

0 comments on commit 34a18cd

Please sign in to comment.