方法一:暴力穷举。显然超时了。90/103。
class Solution { public boolean isHuiwen(String s){ for(int i = 0,j = s.length()-1;i <= j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } public String longestPalindrome(String s) { StringBuffer list = new StringBuffer(); if(s == null || s.length() == 0) return ""; if(s.length() == 1) return s; for(int i = 0; i < s.length();i++){ for(int j = i+1; j < s.length();j++ ){ if(isHuiwen(s.substring(i,j+1))){ if(s.substring(i,j+1).length() > list.length()){ list = list.delete(0,list.length()); list.append(s.substring(i,j+1)); } } } } if(list.length()==0){ return new Character(s.charAt(0)).toString(); }else{ return list.toString(); } } }
对上述方法进行优化,当必须新的子串长度大于已经找到的回文数,才进行判断,否则有无回文都不必判断。(103/103)用例全部通过,超时
class Solution { int len = -1; public boolean isHuiwen(String s,int m,int n){ for(int i = 0,j = s.length()-1;i <= j;i++,j--){ if(s.charAt(i)!=s.charAt(j)){ return false; } } len = n - m; return true; } public String longestPalindrome(String s) { StringBuffer list = new StringBuffer(); if(s == null || s.length() == 0) return ""; if(s.length() == 1) return s; for(int i = 0; i < s.length();i++){ for(int j = i+1; j < s.length();j++ ){ if( j - i < len){ continue; } if(isHuiwen(s.substring(i,j+1),i,j)){ if(s.substring(i,j+1).length() > list.length()){ list = list.delete(0,list.length()); list.append(s.substring(i,j+1)); } } } } if(list.length()==0){ return new Character(s.charAt(0)).toString(); }else{ return list.toString(); } } }