1. 程式人生 > >647. Palindromic Substrings

647. Palindromic Substrings

html lis example IV 回文 exc exe entry 不同

問題描述:

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:

  1. 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; } };

647. Palindromic Substrings