问题描述:
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.
Example 1:
Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
- The input string length won't exceed 1000.
解题思路:
这道题我使用了跟5 Longest Palindromic Substring一样的做法。
与之不同的是,本题要求返回回文子串的个数:
一个长的回文串,如"aabaa"它除去每个单独的字符,长度大于1的子串有:“aba” “aabaa”两个,即 长度/2
也不要忘记每个单独的字符也是一个回文子串。
代码:
class Solution { public: int countSubstrings(string s) { if(s.size() < 2) return s.size(); int ret = s.size(); for(int i = 0; i < s.size(); i++){ if(i-1 > -1){ int cur = calPalindrome(s, i-1, i+1); ret += cur/2; } if(i+1 < s.size() && s[i] == s[i+1]){ int cur = calPalindrome(s, i, i+1); ret += cur/2; } } return ret; } private: int calPalindrome(string &s, int left, int right){ int ret = 0; while(left > -1 && right < s.size()){ if(s[left] != s[right]){ break; } left--; right++; } return right - left - 1; } };