647. Palindromic Substrings

来源:互联网 发布:低空突防航迹规划算法 编辑:程序博客网 时间:2024/05/22 12:07

题目:

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.

解答:

这题是求解一段字符串中有多少个回文子序列。对于求回文子序列,我首先想到一般DP方法,但是好像比较复杂。以下是另外一种方法。遍历字符串,以每一个(两个)字符开始向两遍拓展,如果符合回文,计数就加1;若 两段字符不想当或者越界,则停止循环,看下一个字符。
回文子序列长度可以是奇数,也可以是偶数。所以分两种情况分别求解。

class Solution {public:    int countSubstrings(string s) {        int res = 0;        for (int i = 0; i < s.size(); i++) {            func(i, i, res, s);  // 子字符串为奇数形式,以s[i]开始拓展            func(i, i+1, res, s);  // 子字符串为偶数形式,以s[i]s[i+1]开始拓展        }        return res;    }    void func(int start, int end, int& res, string s) {        while (start >= 0 && end < s.size() && s[start] == s[end]) {            res++;            // 如果仍然未越界且两端字符相等,则继续向两边拓展            start--;              end++;        }    }};
原创粉丝点击