zoukankan      html  css  js  c++  java
  • 647. 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.

    题目含义:找出一个字符串中所有可能出现的回文子串的个数

    方法一:像水的波纹一样,从两个位置(ij)开始依次往外扩散,直到不符合回文为止

     1     private int count;    
     2     
     3     //找到以i,j为中心,往外扩散能构成的回文串个数
     4     private void checkPalindrome(String s, int i, int j) {
     5         while(i>=0 && j<s.length() && s.charAt(i)==s.charAt(j)){    //Check for the palindrome string
     6             count++;    //Increment the count if palindromin substring found
     7             i--;    //To trace string in left direction
     8             j++;    //To trace string in right direction
     9         }
    10     }    
    11     
    12     public int countSubstrings(String s) {
    13         if (s.length()==0) return 0;
    14         for (int i=0;i<s.length();i++)
    15         {
    16             checkPalindrome(s,i,i);
    17             checkPalindrome(s,i,i+1);
    18         }
    19         return count;        
    20     }

     方法二:dp[len][len]  代表[i,j]之间是否构成回文字符串

     1     public int countSubstrings(String s) {
     2         if(s == null || s.length() == 0)
     3             return 0;
     4         int len = s.length();
     5         int res = 0;
     6         boolean[][] dp = new boolean[len][len]; //代表[i,j]之间是否构成回文字符串
     7         for(int i = len - 1; i >= 0; i--){
     8             for(int j = i; j < len; j++){
     9                 //首先i和j位置上的字符要相等 ,其次i和j的距离不超过2,如果超过2了,则要求[i+1,j-1]能构成回文串
    10                 if(s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1])){
    11                     dp[i][j] = true;
    12                     res++;
    13                 }
    14             }
    15         }
    16         return res;     
    17     }
  • 相关阅读:
    ecshop 商品分类下的销售排行
    ecshop批量清除商品的精品新品热销属性
    ECSHOP二次开发之给商品增加新字段
    ECSHOP首页调用文章内的缩略图
    ECSHOP给分类添加代表图
    ECSHOP首页促销商品下显示促销时间
    鼠标点击后更换背景
    ECSHOP如何修改商品评论或留言的日期
    ECSHOP设置指定IP才能登录后台
    ecshop远程图片本地化保存相册图片
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7687046.html
Copyright © 2011-2022 走看看