leetcode

647. 回文子串

2020-08-27  本文已影响0人  geaus

给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。

示例 1:

输入:"abc"
输出:3
解释:三个回文子串: "a", "b", "c"
示例 2:

输入:"aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"

中心扩展法。

    int countSubstrings(string s) {
        int ret = 0;
        for(int i=0; i<s.size(); i++){
            count(s, i, i, ret);
            count(s, i, i+1, ret);
        }
        return ret;
    }

    void count(string& s, int start, int end, int& ret){
        while(start>=0 && end<s.size() && s[start]==s[end]){
            ret++;
            start--;
            end++;
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读