首页 > 其他 > 详细

【LeetCode】 String中的最长回文

时间:2014-04-22 00:17:01      阅读:521      评论:0      收藏:0      [点我收藏+]

java 普通版:

1.正序遍历数组,取得子字符串的首字母。

2.倒序遍历数组,取的子字符串的尾字母。

(这样只要在子循环中第一个出现回文,那么该回文肯定是本次循环的最长的回文)

3.新增数据结构,存储出现最长的那个子串的长度,起始下标和结束下标。

 

/**
 * 
 */
package com.cxm;

/**
 * @author admin
 *
 */
public class PalindromeS
{
	private static String str = "hfjdjajdjhjlshlajdjajdjlsjdlsjiwowjvvmz.zjjfdkdfjjz.lafdiofeqnvkcajdlajiwonvbhdskalhdjfkda;jfdk;ajfdkjfkda;";
	
	public static void main(String[] args)
	{
		PalindromeS PalindromeS = new PalindromeS();
		PalindromeS.findpalindromeS();
	}
	
	public void findpalindromeS(){
		BigSotre bigSotre = PalindromeS.this.getBigSotre() ;
		char[] charArray = str.toCharArray();
		for(int i = 0;i<charArray.length;i++){
			for(int j =charArray.length -1;j>i;j--){
				 if(isPalindrome(charArray,i,j)){
					 bigSotre.store(i, j);
					 break;
				 }
			}
		}
		System.out.println("最大回文长度"+bigSotre.bigSzie+"  起始下标"+bigSotre.startIndex+"  结束下标 "+bigSotre.endIndex);
	}
	
	private class BigSotre{
		int bigSzie;
		
		int startIndex;
		
		int endIndex;
		
		BigSotre(int i,int j,int k){
			this.bigSzie = i;
			this.startIndex = j;
			this.endIndex = k;
			
		}
		
		public BigSotre store(int i ,int j){
			if((j-i+1)>this.bigSzie){
				this.bigSzie = j-i+1;
				this.startIndex = i;
				this.endIndex = j;
			}
			return this;
		}
		
	}
	
	public BigSotre getBigSotre(){
		return new BigSotre(0,0,0);
	}
	
	public boolean isPalindrome(char[] charArray,int i ,int j ){
		int intL = j-i +1;
		int length = (intL>>1)+i;
		while(i<length){
			if(charArray[i]!=charArray[j]){
				return false;
			}
			i++;
			j--;
		}
		return true;
	}
}


 

【LeetCode】 String中的最长回文,布布扣,bubuko.com

【LeetCode】 String中的最长回文

原文:http://blog.csdn.net/cxming007/article/details/24270281

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!