题目描述
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.
解题思路
对整个字符串进行循环访问,每次选取当前字符为中心,往两侧展开看是否相等。如果回文串是偶数的,则选取两个字符为中心展开。
解题代码
#include <string>
using namespace std;
class Solution {
public:
int countSubstrings(string s) {
int res = 0, n = s.length();
for(int i = 0; i < n; i++){
for(int j = 0; i-j >= 0 && i+j < n && s[i-j] == s[i+j]; j++)res++; //substring s[i-j, ..., i+j]
for(int j = 0; i-1-j >= 0 && i+j < n && s[i-1-j] == s[i+j]; j++)res++; //substring s[i-1-j, ..., i+j]
}
return res;
}
};