[LeetCode] Palindromic Substrings

647. Palindromic Substrings

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

  • new solution update 2022.05.22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int countSubstrings(string s) {
string ss = "#";
for(auto& ch : s) {
ss.push_back(ch);
ss.push_back('#');
}
int n = ss.length(), res = 0;
vector<int> dp(n);
int l = 0, r = -1;
for(int i = 0; i < n; i++) {
dp[i] = max(0, min(r - i, (r + l - i >= 0 ? dp[r + l - i] : -1)));
while(i + dp[i] < n and i - dp[i] >= 0 and ss[i-dp[i]] == ss[i+dp[i]])
dp[i]++;
res += dp[i] / 2;
if(i + dp[i] > r) {
r = i + dp[i];
l = i - dp[i];
}
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int compare(string& s, int start, int end) {
int res = 0;
while(start != -1 && end != s.length()) {
if(s[start] == s[end]) {
start--, end++, res++;
} else {
return res;
}
}
return res;
}
public:
int countSubstrings(string s) {
int res = 0;
for(int i = 0; i < s.length(); i++) {
res += 1 + compare(s, i - 1, i + 1) + compare(s, i, i + 1);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/27/PS/LeetCode/palindromic-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.