码迷,mamicode.com
首页 > 其他好文 > 详细

Palindromic Substrings

时间:2017-10-20 14:37:09      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:output   substr   har   you   div   character   substring   aaa   public   

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 };

 

Palindromic Substrings

标签:output   substr   har   you   div   character   substring   aaa   public   

原文地址:http://www.cnblogs.com/wsw-seu/p/7699294.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!