Leetcode算法学习日志-647 Palindromic Substrings

来源:互联网 发布:centos7 yum安装git 编辑:程序博客网 时间:2024/06/11 20:08

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: 3Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: "aaa"Output: 6Explanation: 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;           }};





原创粉丝点击