647. Palindromic Substrings

来源:互联网 发布:盛京时报数据库 编辑:程序博客网 时间:2024/06/10 09:33

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.

分析

每个单字符,自己构成回文字符串。

对字符串的每个位置i,以i为中心,向两边扩展,找出长度为奇数的回文子字符串;

以i为左边扩展的起点,以i+1为右边扩展的起点,找出长度为偶数的子字符串。


代码

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