From 34a18cd321281dc675b41b340ced8614ff01fde8 Mon Sep 17 00:00:00 2001 From: whewchews Date: Sat, 17 Aug 2024 14:52:38 +0900 Subject: [PATCH] 5: palindromic-substrings --- palindromic-substrings/whewchews.ts | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 palindromic-substrings/whewchews.ts diff --git a/palindromic-substrings/whewchews.ts b/palindromic-substrings/whewchews.ts new file mode 100644 index 000000000..294c721f4 --- /dev/null +++ b/palindromic-substrings/whewchews.ts @@ -0,0 +1,35 @@ +function countSubstrings(s: string): number { + // SC: O(N^2) + const dict: Map = 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)