Leetcode算法学习日志-647 Palindromic Substrings

Leetcode 647 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".

题意分析

此题需要找到所有回文的数量,回文的特点是一定有一个中心元素,中心可能是一个,也可能是两个,从中心往两边遍历,看两边元素是否相等。

解法分析

本题先分析可能有的回文个数,回文可以单个元素,两个元素,多个元素,所以如果遍历所有长度的子序列,复杂度很高,如果能降到O(n^2)即理想,考虑遍历每一个元素,以其为中心,由于单个元素是回文,所以count+1,如果其两边元素相等,count+1,继续遍历两边元素,直到不相等或者超出边界;再判断此元素和前一个元素是否相等,如果相等,则count+1,并以这两个相等元素为中心向两侧遍历。c++代码如下:

class Solution {
public:
    int countSubstrings(string s) {
        auto n=s.size();
        int i;
        int count=0;
        int j;
        for(i=0;i<n;i++){
            count++;
            if(i==0)
                continue;
            if((i==n-1)&&(s[i]==s[i-1])){
                count++;
                continue;                
            }
            j=1;
            while(((i-j)>=0)&&(s[i-j]==s[i+j])&&((i+j)<n)){
                count++;
                j++;
            }
            if(s[i]==s[i-1]){
                j=1;
                count++;
                while(((i-j-1)>=0)&&(s[i-j-1]==s[i+j])&&((i+j)<n)){
                    count++;
                    j++;
                }
            }                
        }
        return count;       
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值