Leetcode 5 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.
Solution:
中心扩散法 Spread From Center
时间 O(n^2) 空间 O(1) 外层循环遍历的是子字符串的中心点,内层循环则是从中心扩散,一旦不是回文就不再计算其他以此为中心的较大的字符串。由于中心对称有两种情况,一是奇数个字母以某个字母对称,而是偶数个字母以两个字母中间为对称,所以我们要分别计算这两种对称情况。
public string LongestPalindrome(string s) { if(s.Length ==1) return s; int res = 0; int mx = 0; int left = 0; for(int i = 0;i< s.Length;i++) { //even int j =0; while(i-j>=0 && i+j <s.Length-1) { if(s[i+j+1] == s[i-j]) j++; else break; } if(2*j> mx) { mx = 2*j; left = i - j+1; } //odd int jj =1; while(i-jj>=0 && i+jj <s.Length) { if(s[i+jj] == s[i-jj]) jj++; else break; } if(2*jj -1 >mx) { left = i - jj + 1; mx = 2*jj -1; } } return s.Substring(left, mx); }
Manacher's Algorithm 马拉车算法
https://segmentfault.com/a/1190000002991199
public string LongestPalindrome(string s) { var ss = "@#"; for(int i = 0;i<s.Length;i++) { ss += s[i]; ss += "#"; } ss +="$"; int[] len = new int[ss.Length]; int mx = 0; int po = 0; int resMx = 0; int resId = 0; for (int i = 1; i < ss.Length; i++) { if(mx >i) len[i] =Math.Min(mx - i,len[2*po - i] ) ; else len[i] = 1; while((i+len[i])<ss.Length && ss[i+len[i]] == ss[i - len[i]]) len[i]++; if(i+len[i] >mx) { mx = i+len[i]; po = i; } if (resMx < len[i]) { resMx = len[i]; resId = i; } } return s.Substring((resId - resMx)/2,resMx -1); }