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
原文:http://blog.csdn.net/cxming007/article/details/24270281