LeetCode【5】. Longest Palindromic Substring,longestsubstring
Longest Palindromic Substring
一、題目如下:
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
題目要求給定字串的最大對稱子字串,如“aaabccbacc”的最大對稱子字串為“abccba”。二、思路: 以每個字元或兩個字元的中間作為中心向兩邊比較過去,並判斷是否為對稱子字元。思路很簡單,兩種情況如下:
圖一、兩種對稱情況 ,對於對稱字串,可能出現如上兩種情況。一種為A“偶對稱”,以中隔線互相對稱;另一種為B“奇對稱”,以中間一字元為中心對稱。通過i從0一直掃向字串的尾部,每次前進0.5,並以i為中心,向兩端掃去進行判斷。時間複雜度為O(n^2),最壞情況為整個字串所有字元相同,那麼每次掃都得掃到盡頭。三、Java程式
</pre><pre name="code" class="java">public class Solution { public String longestPalindrome(String s) { int down = 0,up = 0,count = 0; //分別記錄掃字串時的上下區間及字串長度 int sl = s.length(); int maxl = 0; int subDown = 0, subUp = 0; //目標子字串的上下區間 String subS = new String(""); if(sl==0) return ""; //1. 找出目標子字串的中間位置及上下限 for(double i=0; i<=sl-1; i=i+0.5) { down = (int)Math.floor(i); up = (int)Math.ceil(i); if((i%1==0.5)&&sl!=0) //判斷i所屬情況(A或B) { count = 0; }else { count = 1; down--; up++; } //2. 以i為中心向兩邊掃描 while(!(down<0||up>sl-1)) { if(s.charAt(down)!=(s.charAt(up))) { break; //2.1. 當以i為中心對稱的倆字元不相等則跳出掃描 }else{ //2.2. 當以i為中心對稱的倆字元相等則繼續分別向兩邊移動 count+=2; down--; up++; } } //3. 更新最長字串 if(count>maxl) { maxl = count; subDown = down; subUp = up; } } //3.1 由於在掃描時,先移動後再判斷,停止時其實前後都多移動了一個單位,這裡進行一個單位的恢複 subDown++; subUp--; subS = s.substring(subDown,subUp+1); return subS;//返回對稱子字串 }}
擴充學習:該文章介紹了幾種方法Java Longest Palindromic Substring(最長迴文字串)
Leetcode – Longest Palindromic Substring (Java)