LeetCode第5题--最长回文子串

C++

1. 中心扩展算法

要始终记住索引要比真实长度少一,所以要表示真实长度要加一
R-L-1那里是因为当回文时就r++l–,所以r和l最后指的位置时回文子串的前一和后一的位置,算出的真实长度(R-L+1)要减2

class Solution {
public:
    	string longestPalindrome(string s) 
	{
		if (s.length() < 1)
		{
			return "";
		}
		int start = 0, end = 0;
		for (int i = 0; i < s.length(); i++)
		{
			int len1 = expandAroundCenter(s, i, i);     //一个元素为中心
			int len2 = expandAroundCenter(s, i, i + 1); //两个元素为中心
			int len = max(len1, len2);
			if (len > end - start)
			{
				start = i - (len - 1) / 2;
				end = i + len / 2;
			}
		}
		return s.substr(start, end - start + 1);
	}

	int expandAroundCenter(string s, int left, int right)
	{
		int L = left, R = right;
		while (L >= 0 && R < s.length() && s[L] == s[R])
		{// 计算以left和right为中心的回文串长度
			L--;
			R++;
		}
		return R - L - 1; //当回文时就r++l--所以r和l最后指的位置时回文子串的前一和后一的位置
	}
};

Python


class Solution:
    def longestPalindrome(self, s: str) -> str:
        res = ''
        for i in range(len(s)):
            s1 = self.find(s, i, i)       # 以当前字符为中心的最长回文子串
            s2 = self.find(s, i, i+1)     # 以当前字符和下一字符为中心的最长回文子串
            #如果最大长度有变化则更新res
            if max(len(s1), len(s2)) > len(res):
                res = s2 if len(s1) < len(s2) else s1
        return res

    def find(self, s, left, right):
        #找到当前中心的最大长度子串
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return s[left+1:right]    #切片到right的前一个,不包括right
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值