[leetcode]647. Palindromic Substrings
Analysis
跟爸妈一起旅游了一个礼拜,然后就回学校准备开学啦~—— [心塞,这么大了还是很讨厌开学]
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.
给定一个字符串,判断其中包含多少个回文串,这里判断回文串用的是对称轴的方法,即对于一个回文串,长度为偶数时,对称轴为中间的两个字符,整个串以这两个字符为轴对称;长度为奇数时,对称轴为中间的一个字符,整个串以这个字符为轴对称。
Implement
class Solution {
public:
int countSubstrings(string s) {
len = s.size();
cnt = 0;
for(int i=0; i<len; i++){
count(s, i, i);
count(s, i, i+1);
}
return cnt;
}
void count(string s, int left, int right){
while(left>=0 && right<len && s[left]==s[right]){
cnt++;
left--;
right++;
}
}
private:
int cnt;
int len;
};