zoukankan      html  css  js  c++  java
  • 【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;
    	}
    }
    


     

  • 相关阅读:
    “ODBC驱动程序不支持动态记录集”错误的解决
    Pro *C/C++学习笔记(一)
    探讨全局变量的析构顺序
    指针和数组关系初探
    (转)Visual C++开发工具与调试技巧整理
    对利用Session纪录datagrid模板列中CheckBox的状态的一点改进
    大学老师列传
    重读保尔的意义
    Rich Edit控件的使用
    C++程序员常用工具集
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4195231.html
Copyright © 2011-2022 走看看