• 【LeetCode】 String中的最长回文


    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;
    	}
    }
    


     

  • 相关阅读:
    第二阶段个人冲刺总结01
    软件工程学习进度表13
    软件工程学习进度表12
    个人博客(09)
    个人博客(07)
    个人博客(08)
    poj1562 DFS入门
    poj3278 BFS入门
    数组单步运算
    十天冲刺
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4195231.html
Copyright © 2020-2023  润新知