• leetcode 647 回文子串


    package com.example.lettcode.dailyexercises;
    
    /**
     * @Class CountSubstrings
     * @Description 647 回文子串
     * 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
     * 具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
     * <p>
     * 示例 1:
     * 输入:"abc"
     * 输出:3
     * 解释:三个回文子串: "a", "b", "c"
     * <p>
     * 示例 2:
     * 输入:"aaa"
     * 输出:6
     * 解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
     * @Author
     * @Date 2020/8/19
     **/
    public class CountSubstrings {
        /**
         * 动态规划:解法与LeetCode 5.最长回文子串类似
         * (1)dp[i][j]表示从s[i..j]是否为回文子串
         * (2)状态转换:
         *      i:当j-i<3 并且s[i]=s[j]时,即类似abs时,也是回文串
         *      ii: 当s[i]=s[j]并且s[i+1...j-1]是回文串时,s[i...j]是回文串
         */
        public static int countSubstrings(String s) {
            if (s == null || s.length() == 0) return 0;
            int len = s.length();
            // dp[i][j]表示从s[i..j]是否为回文子串
            boolean[][] dp = new boolean[len][len];
            // 所有单个字符都是回文串
            for (int i = 0; i < len; i++) {
                dp[i][i] = true;
            }
            for (int i = len - 2; i >= 0; i--) {
                for (int j = i + 1; j < len; j++) {
                    // j-i <3 && s[i]=s.[j]也是回文串,类似aba
                    dp[i][j] = ((j - i < 3) || dp[i + 1][j - 1]) && s.charAt(i) == s.charAt(j);
                }
            }
            int cnt = 0;
            for (int i = 0; i < len; i++) {
                for (int j = i; j < len; j++) {
                    if (dp[i][j] == true) cnt++;
                }
            }
            return cnt;
        }
    
        public static boolean isSubstring(String s) {
            int len = s.length();
            for (int i = 0; i < len / 2; i++) {
                if (s.charAt(i) != s.charAt(len - i - 1)) return false;
            }
            return true;
        }
    
        public static void main(String[] args) {
            String s = "abc";
            int ans = countSubstrings(s);
            System.out.println("CountSubstrings demo01 result:" + ans);
    
            s = "aaa";
            ans = countSubstrings(s);
            System.out.println("CountSubstrings demo02 result:" + ans);
        }
    }
    
    
  • 相关阅读:
    使用Leangoo玩转故事地图
    用Leangoo做敏捷需求管理
    LEANGOO成员
    LEANGOO卡片
    给WebAPI的REST接口添加测试页面(三)
    使用Win2D在UWP程序中2D绘图(二)
    Visual Studio 2015的“转到定义”和“查看定义”出错的Bug
    使用Win2D在UWP程序中2D绘图(一)
    Windows 10 UWP程序标题栏设置
    .NET 4.6的RyuJIT尾递归优化的Bug
  • 原文地址:https://www.cnblogs.com/fyusac/p/13530634.html
Copyright © 2020-2023  润新知