647. Palindromic Substrings

来源:互联网 发布:两名潜水员失踪知乎 编辑:程序博客网 时间:2024/06/04 17:55

题目

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

Note:

  1. The input string length won't exceed 1000.
分析

需要找出给定字符串的所有可能回文子串,当起始位置不同时,尽管字符一样,也当做不同的回文子串,需要循环遍历每个字符,以当前字符为起始,向左向右检索是否为回文子串,考虑回文子串长度为奇数和偶数的情况,详见:Very Simple Java Solution with Detail Explanation

class Solution {public:    int count=1;//因为要考虑奇数和偶数的回文子串,所以会传入i和i+1,因此i最多到倒数第二个字符,而倒数第一个字符只有本身一个回文子串,所以初始化为1    int countSubstrings(string s) {        if(s.length()==0)            return 0;        for(int i=0;i<s.length()-1;++i){            Palindromic(s,i,i);            Palindromic(s,i,i+1);        }        return count;    }    void Palindromic(string s,int i,int j){        while(i>=0&&j<s.length()&&s[i]==s[j]){            count++;            i--;            j++;        }    }};


原创粉丝点击