1. 程式人生 > >判斷一個數中最大回文數的長度

判斷一個數中最大回文數的長度

i++ length 偶數 判斷 brush while clas stat light

判斷一個數中最大回文數的長度 :例如12332112345654321中最大的回文數是12345654321,長度為11

public static void palindrome(String str) {
		 
	        int len = str.length();  
	        int max = 1;
	        for(int i = 1; i < len; i++){ 
        		int low = i-1;      //偶數情況  
        		int high = i;  
        		while(low >= 0 && high < len && str.charAt(low) == str.charAt(high)){  
	                low--;  
	                high++;  
	            }  
	            if(high-low-1 > max){  
	                max = high-low-1; 
	            } 
	            
        		low = i-1;      //奇數情況  
	            high = i+1;  
	        	while(low >= 0 && high < len && str.charAt(low) == str.charAt(high)){  
	                low--;  
	                high++;  
	            }  
	            if(high-low-1 > max){  
	                max = high-low-1; 
	            }  
	        }  
	        System.out.println(max);  
	}  
	
	public static void main(String[] args) {
		String s = "1234321123565321";  
		palindrome(s);
	}
	

  

判斷一個數中最大回文數的長度