刷题笔记——牛客、LeetCode

一、字符串篇

5. 最长回文子串(longest palindromic substring)

题目:Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000。

提示1:How can we reuse a previously computed palindrome to compute a larger palindrome?

提示2:If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome?

提示3:

Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.

方法一、暴力解法:

只需记录最长回文子串的下标和字符串的长度即可、枚举的时候只需要枚举那些长度大于等于2并且超过最长长度的那些串即可,因此左边界只需要枚举到倒数第二个位置,右边界从左边界加1的地方开始枚举,

C++ 超出时间限制

代码如下:

class Solution {
public:
    string longestPalindrome(string s) {
        if(s.length()<2) {
            return s;
        }
        int str_len = s.length();
        int str_begin = 0;
        int max_length = 1;

        for(int i=0; i < str_len-1; i++) {
            int j = i+max_length;
            for( ; j<str_len; j++) {
                if(validPalindrome(s,i,j)){
                    str_begin = i;
                    max_length = j-i+1;
                }
       
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值