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;
        }
    }
    
  • 相关阅读:
    堆内存和栈内存
    链表
    爬虫---正则表达式
    剑指offer---二维数组中的查找
    基于C#开发的俄罗斯方块
    Java第十天
    软考错题合集之11-05-AM
    软考错题合集之11-11-AM
    软考错题合集之12-05-AM
    GOF之模板模式
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9389331.html
Copyright © 2011-2022 走看看