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

    题目链接 https://leetcode-cn.com/problems/longest-palindromic-substring/

    超时三次,最终选择看题解。

    首先感觉是判断是否是回文这里出了问题,不应该傻傻for循环,要利用子结构。。。。嗐,学了个假dp

    这个是改了题解,顺应自己思路的ac代码,双重循环那里 l++,i++比++i,++l快了36秒,奇怪。

     1 class Solution {
     2 public:
     3     string longestPalindrome(string s) {
     4         int n = s.size();
     5         vector<vector<int>> dp(n, vector<int>(n));
     6         string ans;
     7         for (int l = 0; l < n; ++l) {
     8             for (int i = 0; i + l < n; ++i) {
     9                 int j = i + l;
    10                 if (l == 0) {
    11                     dp[i][j] = 1;
    12                 } else if (l == 1) {
    13                     dp[i][j] = (s[i] == s[j]);
    14                 } else {
    15                     dp[i][j] = (s[i] == s[j] && dp[i + 1][j - 1]);
    16                 }
    17                 if (dp[i][j] && l + 1 > ans.size()) {
    18                     ans = s.substr(i, l + 1);
    19                 }
    20             }
    21         }
    22         return ans;
    23     }
    24 };
    View Code
  • 相关阅读:
    python_控制台输出带颜色的文字方法
    模拟数据库作业
    js笔记
    CSS 笔记
    html 笔记
    必备技能-Git 使用规范流程
    python 闭包
    30个python编程技巧!
    python 面向对象
    python 线程
  • 原文地址:https://www.cnblogs.com/hcl6/p/14015594.html
Copyright © 2011-2022 走看看