本文主要是介绍Leet Code 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.
【算法思路】
1. 最简单的办法就是以i为中心进行扩展回文,分奇数和偶数两种情况。O(n^2)
public class Solution {public String longestPalindrome(String s) {int length = s.length();if(length <= 1)return s;String longest = s.substring(0,1);for(int i = 0; i < length-1; i ++){String p1 = expandAroundCenter(s, i, i);if (p1.length() > longest.length())longest = p1;String p2 = expandAroundCenter(s, i, i+1);if (p2.length() > longest.length())longest = p2;}return longest;}String expandAroundCenter(String s, int c1, int c2) {int left = c1, right = c2;int n = s.length();while (left >= 0 && right <= n-1 && s.charAt(left) == s.charAt(right)) {left--;right++;}return s.substring(left+1, right);}
}
2. O(n)解法。相当巧妙,http://www.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
定义函数
P[i,j] = 字符串区间[i,j]是否为palindrome.
首先找个例子,比如S="abccb",
S= a b c c b
Index = 0 1 2 3 4
P[0,0] =1 //each char is a palindrome
P[0,1] =S[0] == S[1] , P[1,1] =1
P[0,2] = S[0] == S[2] && P[1,1], P[1,2] = S[1] == S[2] , P[2,2] = 1
P[0,3] = S[0] == S[3] && P[1,2], P[1,3] = S[1] == S[3] && P[2,2] , P[2,3] =S[2] ==S[3], P[3,3]=1
......................
由此就可以推导出规律
P[i,j] = 1 if i ==j
= S[i] ==S[j] if j = i+1
= S[i] == S[j] && P[i+1][j-1] if j>i+1
【CODE】
1: string longestPalindrome(string s) {
2: int len = s.size();
3: int P[len][len];
4: memset(P, 0, len*len*sizeof(int));
5: int maxL=0, start=0, end=0;
6: for(int i =0; i< s.size(); i++)
7: {
8: for(int j =0; j<i; j++)
9: {
10: P[j][i] = (s[j] == s[i] && (i-j<2 || P[j+1][i-1]));
11: if(P[j][i] && maxL < (i-j+1))
12: {
13: maxL = i-j+1;
14: start = j;
15: end = i;
16: }
17: }
18: P[i][i] =1;
19: }
20: return s.substr(start, end-start +1);
21: }
这篇关于Leet Code 5 Longest Palindromic Substring的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!