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

 

Note:

  1. The input string length won't exceed 1000.
 1 class Solution {
 2 public:
 3     int countSubstrings(string s) {
 4         //回文子串的数量
 5         if(s.size()==0||s.size()==1)  return s.size();
 6         int sum=0;
 7         for(int i=0;i<s.size();i++)
 8         {
 9             sum+=helper(s,i,i);
10         }
11          for(int i=0;i<s.size()-1;i++)
12         {
13             sum+=helper(s,i,i+1);
14         }
15         return sum;
16     }
17 private:
18     int helper(string s,int c1,int c2)
19     {
20         int i=c1,j=c2;
21         int sum=0;
22         while(i>=0&&j<s.size()&&s[i]==s[j])
23         {
24             sum++;
25             i--;
26             j++;           
27         }
28         return sum;
29     }
30 };

 

posted on 2017-10-20 14:22  wsw_seu  阅读(134)  评论(0编辑  收藏  举报

导航