zoukankan      html  css  js  c++  java
  • 最长回文串

    最长回文串

    给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
    示例 1:
    输入: "babad"
    输出: "bab"
    注意: "aba"也是一个有效答案。
    示例 2:
    输入: "cbbd"
    输出: "bb"

    代码实现

     /**
         * 最长回文子串
         *
         * @param args
         */

        public static void main(String[] args{
            Scanner sc = new Scanner(System.in);
            String s = sc.next();
            System.out.println(longestPalindrome(s));

        }

        public static String longestPalindrome(String s{
            if ("".equals(s)) {
                return "";
            }
            int len = s.length();
            if (len == 1) {
                return s;
            }
            int sLength = 1;
            int start = 0;
            int[][] db = new int[len][len];
            for (int i = 0; i < len; i++) {
                //定义初始化状态
                db[i][i] = 1;
                if (i < len - 1 && s.charAt(i) == s.charAt(i + 1)) {
                    db[i][i + 1] = 1;
                    sLength = 2;
                    start = i;
                }
            }
            for (int i = 3; i <= len; i++) {
                for (int j = 0; j + i - 1 < len; j++) {
                    int end = j + i - 1;
                    if (s.charAt(j) == s.charAt(end)) {
                        db[j][end] = db[j + 1][end - 1];
                        if (db[j][end] == 1) {
                            start = j;
                            sLength = i;
                        }
                    }
                }
            }
            return s.substring(start, start + sLength);
        }
  • 相关阅读:
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    72. Edit Distance
    583. Delete Operation for Two Strings
    582. Kill Process
    indexDB基本用法
    浏览器的渲染原理
    js实现txt/excel文件下载
    git 常用命令
    nginx进入 配置目录时
  • 原文地址:https://www.cnblogs.com/wuhen8866/p/11913143.html
Copyright © 2011-2022 走看看