寻找最大的回文字符串

寻找最大的回文字符串,例如字符串adcdedco,那么最大的回文子串就是cdedc。

        其实现代码如下:

package com.threeTop.www;

/**
 * 判断一个字符串是否为回文串
 * @author wjgs
 *
 */
public class StringUtils {
	/**
	 * 判断回文字符串
	 * @param str
	 * @return
	 */
	public static boolean isPalindrome(String str)
	{
		if(str==null||str.length()==0)
		{
			throw new RuntimeException("字符串为空");
		}
		int mid=(str.length()-1)/2;
		for(int i=0;i<=mid;i++)
		{
			if(str.charAt(i)!=str.charAt(str.length()-1-i))
			{
				return false;
			}
		}
		
		return true;
		
	}
	
	/**
	 * 计算回文字符的最大子串的长度
	 * @param str
	 * @return
	 */
	public static int longestPalindrome(String str)
	{
		if(str==null||str.length()==0)
		{
			throw new RuntimeException("字符串为空");
		}
		int max=0,current=0,length=str.length();
		//循环每个字符为回文的中点
		for(int i=0;i<length;++i)
		{
			
			for(int j=0;i-j>=0&&i+j<length;j++)
			{ 
				if(str.charAt(i-j)!=str.charAt(i+j))
				{
					break;
				}
				current=j*2+1;
			}
			if(current>max)
			{
				max=current;
			}
			
			current=0;
			
			for(int j=0;(i-j>=0)&&(i+j+1<length);j++)
			{
				if(str.charAt(i-j)!=str.charAt(i+j+1))
				{
					break;
				}
				current=j*2+2;
			}
			if(current>max)
			{
				max=current;
			}
		}
		return max;
	}
	public static void main(String []args)
	{
		System.out.println(StringUtils.isPalindrome("abcba"));
		System.out.println(StringUtils.isPalindrome("abccba"));
		System.out.println(StringUtils.isPalindrome("abdca"));
		
		//判断最长的回文串
	    System.out.println("最长的回文串长度:"+StringUtils.longestPalindrome("abcdefgfedcgcda"));
	}

}


   

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值