647. Palindromic Substrings

Posted yaoyudadudu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了647. Palindromic Substrings相关的知识,希望对你有一定的参考价值。

问题描述:

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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 647: Palindromic Substrings

LeetCode 647. Palindromic Substrings

647. Palindromic Substrings

[LC] 647. Palindromic Substrings

647. Palindromic Substrings

LeetCode 647. 回文子串(Palindromic Substrings)