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

    给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

    示例 1:

    输入: "babad"
    输出: "bab"
    注意: "aba" 也是一个有效答案。
    示例 2:

    输入: "cbbd"
    输出: "bb"

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-palindromic-substring
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    // 解题思路:s[j][i] = (s[j] == s[i]) + s[j + 1][i - 1]
    // 并且当j - i < 3时,(j - 1 - (i + 1)) + 1 < 2时,一定是为正确的
    func longestPalindrome(s string) string { length := len(s) if length <= 1 { return s } dp := make([][]bool, length) start := 0 maxlen := 1 // 动态规划解法 for i := 0; i < length; i++ { dp[i] = make([]bool, length) dp[i][i] = true } for i := 1; i < length; i++ { for j := 0; j < i; j++ { if (s[j] == s[i]) {
              // 注意理解这个
    if (i - j < 3) { dp[j][i] = true } else { dp[j][i] = dp[j+1][i-1] } } else { dp[j][i] = false } if (dp[j][i]) { tempLen := i - j + 1; if (maxlen < tempLen) { start = j maxlen = tempLen } } } } return s[start:start+maxlen] }
  • 相关阅读:
    oracle用户被锁
    Docker入门
    物化视图
    MySQL报错:Packets larger than max_allowed_packet are not all
    ORA-01555 快照过旧
    mysql授予权限
    CentOS7.4安装部署KVM虚拟机
    前端面试题收藏
    CoffeeScript 学习笔记
    spring学习笔记(四)
  • 原文地址:https://www.cnblogs.com/cjjjj/p/12853995.html
Copyright © 2011-2022 走看看