https://leetcode.com/problems/palindromic-substrings/description/
Solution 1. Moving the center of the palindrome and count.
int countSubstrings(string s) {
int n = s.size();
int res = 0;
for(int i=0; i<n; i++) {
for(int j=0; i-j>=0 && i+j<n; j++) {
if(s[i-j] == s[i+j]) res++;
else break;
}
for(int j=0; i-j>=0 && i+j+1<n; j++) {
if(s[i-j] == s[i+j+1]) res++;
else break;
}
}
return res;
}
Solution 2. Recursion. Slow because of duplicated comparisons.
int count(string& s, int n) {
if(n<2) return n;
int m = count(s, n-1);
for(int lo = 0; lo<n; lo++) {
int i=lo, j = n-1;
for(; i<=j; i++, j--) {
if(s[i]!=s[j]) break;
}
m += i>j;
}
return m;
}
int countSubstrings(string s) {
return count(s, s.size());
}
No comments:
Post a Comment