《Java算法系列》最长回文数

本文介绍了一种寻找字符串中最长回文子串的方法。通过从每个字符出发,分别假设回文串长度为奇数和偶数两种情况,向两边扩展来确定最长回文子串。该方法适用于字符串最大长度为1000的情况。

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

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 的最大长度为1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba"也是一个有效答案。

示例 2:

输入: "cbbd"
输出: "bb"
 public String longestPalindrome(String s) {
	        int curstart=0;//current start 当前开始位置
	        int curend=0;//current end
	        int current=0;//current length 
	        int max=0;//最大的回文串长度
	        int maxstart=0;//最大的开始位置
	        int len=s.length();
	        int i=0;
	        for(i=0;i<len;i++){//从第i个位置开始向两面依次便利
	            curstart=i;//假设回文串长度是奇数
	            curend=i;//从第i个位置开始向两面依次便利
	            while(curstart>=00&&curend<len){
	                if(s.charAt(curstart)==s.charAt(curend)){
	                    curstart--;
	                    curend++;
	                }
	                else
	                    break;
	            }   
	            current=curend-curstart-1;//当前长度 
	            if(current>max){//替换最长回文串
	                max=current;
	                maxstart=curstart+1;
	            }
	            curstart=i;//假设回文串长度是偶数数
	            curend=i+1;//从第i,i+1个位置开始向两面依次便利
	             while(curstart>=00&&curend<len){
	                if(s.charAt(curstart)==s.charAt(curend)){
	                    curstart--;
	                    curend++;
	                }
	                 else
	                     break;
	            }   
	            current=curend-curstart-1; 
	            if(current>max){
	                max=current;
	                maxstart=curstart+1;
	            }
	        }
	        
	        String result=s.substring(maxstart,maxstart+max);
	        return result;
	    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值