Leetcode647. 计算回文子字符串数目

来源:互联网 发布:淘宝上买车险 编辑:程序博客网 时间:2024/06/10 17:46

Leetcode647. 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”.

解题分析

一拿到这道题,可能第一想法就是感觉这道题好麻烦呀,需要找出该字符串的所有子字符串,再分别对这些子字符串进行判断。的确,和我们的感觉一样,这样的做法确实是很普通的,虽然可以AC,但时间复杂度太大了,为O(n^3)。那么有没有更好的做法呢?其实是有的。

我们可不可以这样想,在遍历字符串的时候,考虑一下对每个字符进行左右扩展?(比如aaa,对中间的a进行左右扩展得到aaa)这样的话,就不需要再找子字符串再进行判断了,我们只需在遍历的时候,对每个字符的左方和右方的字符进行判断,如果相同就继续往两侧扩展直到一方到达该字符串的边界;如果不同,则直接结束循环,这样时间复杂度就有效地变成O(n^2)了。
但其实上面这样做的话只考虑到了字符串长度为奇数的情况,偶数的情况没有考虑(比如aa)。但其实做法跟上面完全相同,这里我就不再细述了。两种情况相加,就是最后的结果。

源代码

class Solution {public:    int count = 0;    int countSubstrings(string s) {        int i, size = s.size();        for (i = 0; i < size; i++) {            extend(s, i, i);            extend(s, i, i + 1);        }        return count;    }    void extend(string s, int left, int right) {        while (left >= 0 && right < s.size() && s[left] == s[right]) {            count++;            left--;            right++;        }    }};

以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~

原创粉丝点击