题5Longest Palindromic Substring

本文介绍了一种高效算法来找出字符串中的最长回文子串。该算法通过从每个字符为中心向两边扩展来检查所有可能的回文串,并记录最长的那个。

摘要生成于 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, and there exists one unique longest palindromic substring.

本体可以使用动态规划去解答,但是我用了之后没能AC,也可以使用从中间向两边延伸去查找最长回文子串。先提供第二种方式的解答,通过提交


public class Solution {
public String longestPalindrome(String s) {
        int max = Integer.MIN_VALUE;//最长回文子串长度;
        String result = "";
        for(int i=0;i<s.length();i++){
        	//奇数中心展开
        	String temp1 = expandFromCenterToEdge(s, i, i);
        	if(max<temp1.length()){
        		max = temp1.length();
        		result = temp1;
        	}
        	//偶数展开
        	String temp2 = expandFromCenterToEdge(s, i, i+1);
        	if(max<temp2.length()){
        		max = temp2.length();
        		result = temp2;
        	}
        }
		return result;
    }
	//写一个中间向两边扩展程序
	public String expandFromCenterToEdge(String str,int l,int r){
		int left = l;
		int right = r;
		//while循环是为了找到最长的串;
		while(left>=0&&right<=str.length()-1&&str.charAt(left)==str.charAt(right)){
			left--;
			right++;
			//System.out.println(left+"---"+right);
		}
		return str.substring(left+1,right);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值