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;
        }
    }
    
  • 相关阅读:
    @@IDENTITY 存储过程
    ASP.NET的Cookie和Session
    数据格式设置表达式
    DataTable类(MSDN)
    用静态变量代替appliction
    C cgi url 编码解码问题
    C#视频头操作
    c#网页抓取
    c语言字符串分隔
    CGI c 上传文件
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9389331.html
Copyright © 2011-2022 走看看