演算法題(二):找出最長對稱子串
阿新 • • 發佈:2019-01-27
做法與找出兩個字串的最長公共子串相似。先得到字串的反轉,再利用求最長公共子串的方法來求最長對稱子串。
public static void fun1(String str1) { if(str1==null ||str1.length()==0) { return; } String str2 = verse(str1); fun2(str1, str2); } public static String verse(String str) { String string = ""; if(str==null ||str.length()==0) { return string; } for(int i=str.length()-1; i>=0; i--) { string += str.charAt(i); } return string; } public static void fun2(String str1, String str2){ if(str1 == null || str2 == null || str1.length() == 0 || str2.length() == 0){ return; } int len1 = str1.length(); int len2 = str2.length(); String longest = ""; int length = 0; for(int i=0; i<len1; i++){ int index1 = i; for(int j=0; j<len2; j++){ String temp = ""; if(str1.charAt(index1) == str2.charAt(j)){ temp += str1.charAt(index1); int index2 = index1+1; for(int k=j+1; k<len2; k++){ if(index2<len1 && str1.charAt(index2) == str2.charAt(k)){ temp += str1.charAt(index2); index2++; }else{ break; } } if(temp.length() > length){ length = temp.length(); longest = temp; } } } } System.out.println(length); System.out.println(longest); }
輸入:"aabbbbcc"
輸出:4 bbbb