zoukankan      html  css  js  c++  java
  • Leetcode: Palindromic Substrings

    647. Palindromic Substrings
    Medium
    
    1656
    
    85
    
    Favorite
    
    Share
    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:
    
    The input string length won't exceed 1000.
     

    DP:

     1 class Solution {
     2     public int countSubstrings(String s) {
     3         if (s == null || s.length() == 0) return 0;
     4         int res = 0;
     5         boolean[][] dp = new boolean[s.length()][s.length()];
     6         for (int i = s.length() - 1; i >= 0; i --) {
     7             for (int j = i; j < s.length(); j ++) {
     8                 if (s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1])) {
     9                     dp[i][j] = true;
    10                     res ++;
    11                 }
    12             }
    13         }
    14         return res;
    15     }
    16 }

    Extend palindrome: (better)

     1 public class Solution {
     2     int count = 0;
     3     
     4     public int countSubstrings(String s) {
     5         if (s == null || s.length() == 0) return 0;
     6         
     7         for (int i = 0; i < s.length(); i++) { // i is the mid point
     8             extendPalindrome(s, i, i); // odd length;
     9             extendPalindrome(s, i, i + 1); // even length
    10         }
    11         
    12         return count;
    13     }
    14     
    15     private void extendPalindrome(String s, int left, int right) {
    16         while (left >=0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
    17             count++; left--; right++;
    18         }
    19     }
    20 }
  • 相关阅读:
    北京爱丽丝幻橙科技有限公司
    红杉资本中国基金:创业者背后的创业者
    关于我们_ | 腕表时代watchtimes.com.cn
    当你想放弃的时候,问一下自己你尽力了吗
    李圣杰_百度百科
    范思哲
    DOM Traversal Example | Documentation | Qt Project
    关于QT中evaluateJavaScript()函数返回值的处理问题
    JS获取整个HTML网页代码
    javascript
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/11612467.html
Copyright © 2011-2022 走看看