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;
        }
    }
    
  • 相关阅读:
    题解【51nod 1290 Counting Diff Pairs】
    题解【luogu3709 大爷的字符串题】
    数据库唯一索引冲突不抛出异常的两种方式
    git 查看远程分支最后一次提交时间
    Java占位符
    IntelliJ IDEA注册码
    git忽略本地文件
    ThreadPoolExecutor参数
    MyBatis是如何解决Sql注入的
    Java 泛型
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9389331.html
Copyright © 2011-2022 走看看