【LeetCode】5. Longest Palindromic Substring

本文介绍了一种寻找字符串中最长回文子串的有效算法。通过以每个字符或每组相邻字符为中心向两边扩散的方式,该算法能在O(n^2)的时间复杂度内找到答案。文章提供了详细的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

分析:

题目让输出最长回文子串,最容易想到的方法是:

以每一个元素或每两个相邻元素为中心向两端延伸,记录曾今出现过的最长的回文串,时间复杂度为O(n^2)

还有一种算法能线性时间内解决问题,但是不太理解,这里先不介绍

 

代码:

class Solution {
public:
    string longestPalindrome(string s) {
		string temp, result;
		
    	for (int i = 0; i < s.size(); ++i) {
    		temp = maxPalindrome(s, i, i);
    		if (temp.size() > result.size()){
    			result = temp;
			}
			
			temp = maxPalindrome(s, i, i+1);
			if (temp.size() > result.size()){
    			result = temp;
			}
		}
		return result;
    }
    
    string maxPalindrome(const string& s, int left, int right) {
		while (left >= 0 && right < s.size()) {
    		if (s.at(left) != s.at(right)) {
    			break;
			}
			-- left;
			++ right;
		}
		return s.substr(left + 1, right - left - 1);
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值