zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    UVA
    UVALive
    找一
    买书最低价格
    NABCD模型分析
    二维数组--首尾
    结对开发---环
    结对开发---二维数组
    电梯设计需求调研报告
    数组求和(2)
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/7699294.html
Copyright © 2011-2022 走看看