Palindromic Substrings

版权声明:仅供参考与学习交流 https://blog.csdn.net/lym940928/article/details/89357108

1,题目要求

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.

给定一个字符串,您的任务是计算此字符串中的回文子串数。

具有不同起始索引或结束索引的子字符串被计为不同的子字符串,即使它们由相同的字符组成。

2,题目思路

对于这道题,要求计算一个字符串中的回文形式的子串有多少。

其中,单个字符也是一个回文。
因此,原则上我们要对整个字符串中所有的子串进行一个穷举,并依次判断它们是否是回文。

  • 因为回文是一种对称结构,因此,我们采取从中间向两边进行判断的方式会比较合适。
    比如,对于字符串:
    abcba
    我们如果从c开始判断,那么,就可以得到:
    c,bcb,abcba
    这三个回文串了。当然,它还有a,b,a,b这四个回文串(因为索引位置不同,所以也算作是不同的回文)

另外,

  • 回文的判断还和字符串的长度是奇数还是偶数有很大关系
    比如abbaabcba,在判断上就不同。

于是在实现上,我们可以定义一个helper函数,分别取字符串的每个位置作为“中间位置”,然后定义left和right分别向字符串左端和右端进行扩展判断;同时,在扩张的过程中,还会有奇数与偶数的区别,因此,我们还需要区别对待。

3,代码实现

static const auto s = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    int countSubstrings(string s) {
        int counter = 0;
        if(s.empty())
            return 0;
        for(int i = 0;i<s.size();i++){
            counterHelper(i,i,s,counter);   //子串长度为奇数
            counterHelper(i,i+1,s,counter); //子串长度为偶数
        }
        return counter;
    }
private:
    void counterHelper(int left, int right, string s, int &count){
        while(left>=0 && right<=s.size()-1 && s[left] == s[right]){
            count++;
            left--;
            right++;
        }
        return;
    }
};

猜你喜欢

转载自blog.csdn.net/lym940928/article/details/89357108
今日推荐