Skip to content

Commit bfed15c

Browse files
Jeehay28Jeehay28
authored andcommitted
Add palindromic-substrings solution in TS
1 parent 5556875 commit bfed15c

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

palindromic-substrings/Jeehay28.ts

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// TC: O(n^2)
2+
// SC: O(1)
3+
function countSubstrings(s: string): number {
4+
// Treat each index as the center of potential palindromic substrings
5+
let cnt = 0;
6+
7+
for (let i = 0; i < s.length; i++) {
8+
let start = i;
9+
let end = i;
10+
11+
// Check for odd-length palindromes centered at i
12+
while (start >= 0 && end < s.length && s[start] === s[end]) {
13+
cnt++;
14+
start--; // <----
15+
end++; // ----->
16+
}
17+
18+
// Check for even-length palindromes centered between i and i + 1
19+
start = i;
20+
end = i + 1;
21+
22+
while (start >= 0 && end < s.length && s[start] === s[end]) {
23+
cnt++;
24+
start--;
25+
end++;
26+
}
27+
}
28+
29+
return cnt;
30+
}
31+
32+
// TC: O(n^2)
33+
// SC: O(n^2)
34+
/*
35+
function countSubstrings(s: string): number {
36+
// dp[(start, end)] = s[start] === s[end] && dp[(start + 1, end - 1)]
37+
38+
// A new starting character + an existing palindromic substring + a new ending character
39+
// start dp[(start + 1, end - 1)] end
40+
41+
const dp = new Map<string, boolean>();
42+
43+
for (let end = 0; end < s.length; end++) {
44+
// start ranges from end down to 0
45+
for (let start = end; start >= 0; start--) {
46+
const key = `${start}-${end}`;
47+
if (start === end) {
48+
// "a"
49+
dp.set(key, true);
50+
} else if (start + 1 === end) {
51+
// "aa"
52+
dp.set(key, s[start] === s[end]);
53+
} else {
54+
const prevKey = `${start + 1}-${end - 1}`;
55+
dp.set(key, s[start] === s[end] && dp.get(prevKey) === true);
56+
}
57+
}
58+
}
59+
60+
let cnt = 0;
61+
62+
for (const [key, value] of dp.entries()) {
63+
if (value) {
64+
cnt++;
65+
}
66+
}
67+
68+
return cnt;
69+
}
70+
*/
71+
72+
// TC: O(n^3)
73+
// SC: O(1)
74+
// function countSubstrings(s: string): number {
75+
// const isPalindromic = (left: number, right: number) => {
76+
// while (left < right) {
77+
// if (s[left] !== s[right]) return false;
78+
79+
// left++;
80+
// right--;
81+
// }
82+
83+
// return true;
84+
// };
85+
86+
// let cnt = 0;
87+
88+
// for (let i = 0; i < s.length; i++) {
89+
// for (let j = i; j < s.length; j++) {
90+
// if (isPalindromic(i, j)) {
91+
// cnt++;
92+
// }
93+
// }
94+
// }
95+
96+
// return cnt;
97+
// }

0 commit comments

Comments
 (0)