leetcode problem 647. Palindromic Substrings

本文介绍了一种高效算法,用于计算给定字符串中所有回文子串的数量。通过利用回文串的对称特性,该算法能够显著减少计算时间。

Description

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.

Solution

看到题目第一个想法是觉得:“哇,直接一个一个算复杂度肯定很高,必须想办法把已经算出来的palindromic substrings利用起来。“

动归:貌似有些不对

  • 事实上,因为回文串是对称的,给定一个回文串,我们判断下一个字串是否也是回文串,可以利用两个字串的重复的部分(即串的中心一致的部分),往已有的回文串两端向外判断即可:

  • 如已知:abcba是回文串,那么只要从两端继续看一个字符是不是相同的,若是xabcbax,就是下一个回文串,若是xabcbay,则不是回文串。

所以思路是,遍历s,以每一个字符为中心,从中心向两边比较字符即可

注意:中心也可以是两个字符(即substring的长度是偶数)

代码如下:

class Solution {
public:
    int countSubstrings(string s) {
        int res = 0 ;
        int len = s.size();
        if(len == 0) return 0;
        
        for (int i = 0 ; i < len ; ++i)
        {
            for(int j = 0 ; j < len ; ++ j)
            {
                if( i-j<0 || i+j >=len) break;
                if(s[i-j]==s[i+j]) ++res;
                else break;
            }
        }
        for (int i = 0 ; i < len - 1; ++i)
        {
            for (int j = 0 ; j < len ; ++j)
            {
                if( i-j<0 || i+j+1 >= len) break;
                if(s[i-j]==s[i+j+1]) ++res;
                else break;
            }
        }
        return res;
        
    }
};

结果:

Runtime: 4 ms, faster than 100.00% of C++ online submissions for Palindromic Substrings.
Memory Usage: 8.4 MB, less than 99.58% of C++ online submissions for Palindromic Substrings.

20190330

tbc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值