最長迴文字串-Java實現
阿新 • • 發佈:2019-01-10
一、問題描述
迴文字串定義:如果一個字串正著讀和反著讀是一樣的,那它就是迴文串例如:aba 、 abcba 。
要求:
給出一個字串:asdsaasa
返回一個最長的迴文字串:asdsa
二、解法(迴文字串為奇數)
public class Test { public static void main(String[] args) { String str = "sgfsasaopoiuydfghgfdtrewqirgabnirweir"; System.out.println("答案是:"+searchMaxOddStr(str)); } /** * 查詢最長迴文字串。@author YYM * 只能查詢到如"asdsa"型別的字串(總長度為奇數)。 * 而無法查詢"asddsa"型別的(總長度為偶數)。 * 若要查詢asdsa型別的,請對原字串資料進行處理。 * @param str 待分析的字串 * @return 結果字串 */ public static String searchMaxOddStr(String str) { if (str.equals("")) { return ""; } String answer;//答案字串 int maxLen = 0;//存放當前迴文字串的"半徑". int maxCenter = 0;//存放當前迴文字串的中心。 int nowCenter=0; int nowLen =0; boolean flag = true; char[] list = str.toCharArray(); for(nowCenter = 0;nowCenter< list.length;) { while(flag) {//開始執行一箇中心點的判斷 if((nowCenter-nowLen)>=0 && nowCenter+nowLen<list.length) {//防止越界 if(list[nowCenter-nowLen]==list[nowCenter+nowLen]) { if(maxLen<nowLen) { maxLen = nowLen; maxCenter = nowCenter; } nowLen++; }else flag=false; }else flag =false; } nowCenter++;//判斷下一個 flag = true;//恢復初始狀態 nowLen=1;//恢復初始長度 } answer = str.substring(maxCenter-maxLen,maxCenter+maxLen+1);//擷取 return answer; } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
演算法分析:由於是挨個遍歷每個字元,然後往兩邊擴充套件比較,所以時間複雜度為O(n^2)..
三、如果最長迴文是偶數呢?
簡單,解決辦法是把字串每一個字元之間新增一個不可能出現在字串中的符號,再傳入方法裡:
如:asddsaasasa
改成:#a#s#d#d#s#a#a#s#a#s#a#
再傳入上面寫的方法,得到返回字串後再去掉“#”即可。