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     }
  • 相关阅读:
    MySQL百万级数据量分页查询方法及其优化
    聊一聊二维码扫描登录原理
    在吗?认识一下JWT(JSON Web Token) ?
    怎样和领导汇报工作,更容易获得升职加薪?谈谈和领导汇报的艺术
    javascript sleep pause 实现
    google 根据地址得ip 并显示
    javascript 闭包
    javascript 对象 telecom
    javascript 对象
    google maker 标注
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7687046.html
Copyright © 2011-2022 走看看