《leetcode : 647. 回文子串 思考分析双指针解法》

93 阅读1分钟

647. 回文子串

在这里插入图片描述
如何确定是回文串:
找中心然后往两边扩散,判断是否对称即可。
在遍历中心点的时候,注意中心点可以是一个元素也可以是两个元素。

class Solution {
public:
    int cal_two_extend(const string& s,int i,int j,int n)
    {
        int res = 0;
        //以(i+j)/2为中心点,向左右扩散,计算该中心点构成的回文子串数目
        while(i >= 0 && j < n && s[i] == s[j])
        {
            i--;
            j++;
            res++;
        }
        return res;
    }
    int countSubstrings(string s) {
        int len = s.size();
        int result = 0;
        for(int i = 0; i < len; i++)
        {
            result += cal_two_extend(s,i,i,len);
            result += cal_two_extend(s,i,i+1,len);
        }
        return result;
    }
};