zoukankan      html  css  js  c++  java
  • 【Leetcode】647. Palindromic Substrings

    Description

    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.

    Discusss

    回文字符串可以分为长度为1,2,3来分别讨论。dp[i][j]为回文字符串时,dp[i-1][j+1]是否为回文字符串只需判断i-1和j+1处的字符串是否相等。
    所以可得状态方程dp[i][j] = dp[i + 1][j - 1] && c[i] == c[j] ? true : false;

    Code

    class Solution {
        public int countSubstrings(String s) {
            if (s == null || s.length() == 0) { return 0; }
            int n = s.length();
            boolean[][] f = new boolean[n][n];
            f[0][0] = true;
            char[] c = s.toCharArray();
            int count = 1;
            for (int i = 1; i < n; i++) {
                f[i][i] = true;
                count++;
                if (c[i] == c[i-1]) {
                    f[i-1][i] = true;
                    count++;
                }
            }
    
            for (int i = 2; i < n; i++) {
                for (int j = 0; j < i - 1; j++) {
                    f[j][i] = f[j + 1][i - 1] && (c[j] == c[i] ? true : false);
                    if (f[j][i]) {
                        count++;
                    }
                }
            }
            return count;
        }
    }
    
  • 相关阅读:
    Java开发环境搭建
    MySQL优化
    js正则表达式,验证身份证
    获取urlc参数
    Oracle解锁
    Qt 常用类 (4)—— QPoint
    Qt 常用类——QStandardItemModel
    Qt QTableWidget用法总结
    Qt 随机数
    C++ static类成员,static类成员函数
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9389331.html
Copyright © 2011-2022 走看看