Leetcode学习笔记(5. 最长回文子串)

本文介绍了一种高效算法,用于在给定字符串中寻找最长的回文子串。通过反向思维,算法检查字符串的每个字符及其相邻字符,确定回文串的中心位置和长度。算法使用两个辅助函数来分别处理奇数和偶数长度的回文串,最终返回最长回文子串。

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

在这里插入图片描述
两种情况考虑,反向思维:

class Solution {
public:
	string longestPalindrome(string s) {
		if (s.size() <= 1)
			return s;
		int mid = 0;
		int max_length = 1;
		for (int i = 0; i<s.size() - 1; i++) {
			int temp1 = funt(s, i, i);
			int temp2 = funt(s, i, i + 1);
			if (temp1>max_length || temp2>max_length) {
				mid = i;
				max_length = temp1>temp2 ? temp1 : temp2;
			}
		}
		if (max_length % 2 != 0)
			return s.substr(mid - max_length / 2, max_length);
		else
			return s.substr(mid - max_length / 2 + 1, max_length);
	}
private:
	int funt(string &s, int L, int R) {
		int out = 0;
		while (L >= -1 && R<=s.size()) {
			if (L >= 0 && R < s.size()) {
				if (s[L] == s[R]) {
					L--; R++;
				}
				else {
					out = R - L - 1;
					break;
				}
			}
			else {
				out = R - L - 1;
				break;
			}
		}
		return out;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值