[LeetCode ]Longest Palindromic Substring
阿新 • • 發佈:2018-11-17
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
題意:找出一個字串中最長的迴文串
思路:最高效的方法就是馬拉車演算法,不過這道題資料量比較小,直接列舉迴文串的中心字元,以中心字元向兩邊擴充套件,知道向兩邊擴充套件的字元不相等,這裡為了避免奇數和偶數兩種情況的討論,也利用到了馬拉車的部分思想,給每兩個連續的字元中間加一個特殊字元,首尾再加兩個不一樣的特殊字元。
Java程式碼:
public class Solution { public String longestPalindrome(String s) { if(s.equals("")) return ""; String ss,ans; ss = ans = ""; int len = s.length(); ss += "~"; for(int i = 0; i < len; i++) { ss += s.charAt(i); ss += '$'; } ss += '@'; int Max,_l,_r,l,r,cnt; Max = _r = _l = 0; //System.out.println(ss); for(int i = 1; i < ss.length() - 1; i++) { if(ss.charAt(i) != '$') cnt = 1; else cnt = 0; l = i - 1; r = i + 1; while(ss.charAt(l) == ss.charAt(r)) { if(ss.charAt(l) != '$') cnt += 2; l--; r++; //System.out.println(l + " " + r); } if(Max < cnt) { Max = cnt; _l = l + 1; _r = r - 1; } } for(int i = _l; i <= _r; i++) { if(ss.charAt(i) != '$') { ans += ss.charAt(i); } } return ans; } }
C程式碼,返回字串要用malloc來申請記憶體,傳入的字串可能為空,要特判一下,不然會RE。
char* longestPalindrome(char* s) { if(strcmp(s,"") == 0) { return ""; } char ss[2015]; int len = strlen(s); int Max = 0,i; ss[0] = '~'; int cnt = 1; for(i = 0; i < len; i++) { ss[cnt++] = s[i]; ss[cnt++] = '$'; } int left = 1,right = cnt - 2; int al,ar; char* ans = (char*) malloc(sizeof(char) * 1005); for(i = left; i <= right; i++) { if(ss[i] != '$') cnt = 1; else cnt = 0; int l = i - 1,r = i + 1; while(l >= left && r <= right && ss[l] == ss[r]) { if(ss[l] != '$') { cnt += 2; } l--,r++; } if(Max < cnt) { Max = cnt; if(ss[l] != ss[r]) { l++,r--; } al = l; ar = r; } } cnt = 0; for(i = al; i <= ar; i++) { if(ss[i] != '$') { ans[cnt++] = ss[i]; } } ans[cnt++] = '\0'; return ans; }