LeetCode Longest Palindromic Substring, Nov 11 '11
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.思路:回文的递归在于:去掉两头还是回文。基于这个思路,对每个点i, 计算以i为中心(奇数回文)或者以i为中心偏右(偶数回文)能扩展的最长长度,一旦出现不是回文,break就行了。最坏情况下还是要O(n^2),但是比我一开始用数组存结果快,能过大集合了。
- string longestPalindrome(string s) {
- string res;
- if(s.empty()) return res;
- int start = 0, n = s.length();
- int longest = 1;
- for(int i = 1; i < n; i++){
- //j in center
- for(int j = 1; j <= min(i, n-i-1); j++){
- if(s[i+j] != s[i-j]){
- if( longest < 2*j - 1){
- start = i - j + 1; longest = 2*j - 1;
- }
- break;
- }
- if(j == min(i,n-i-1) && s[i+j] == s[i-j]){
- if(longest < 2*j + 1 ){
- start = i - j ; longest = 2*j + 1;
- }
- }
- }
- //i in right center
- for(int j = 0; j < min(i,n-i); j++ ){
- if(s[i+j]!= s[i-1-j]){
- if(longest < 2*j ){
- start = i - j ; longest = 2*j ;
- }
- break;
- }
- if(j == min(i,n-i) - 1 && s[i+j] == s[i-1-j]){
- if(longest < 2*(j+1) ){
- start = i - 1 - j ; longest = 2*(j+1) ;
- }
- }
- }
- }
- res = s.substr(start, longest);
- return res;
这是一开始写的用数组存结果的,这个方法的缺点是有些不必要的计算,比如abca知道b!=c之后,还是要再设定abca的值为false,而用上面改进方法,知道b!=c后,就不用再考虑abca了。
string longestPalindrome(string s) {
string res;
int start = 0, end = 0, longest = 1;
if(s.empty()) return res;
vector<vector<bool> > A(s.length(),vector<bool>(false));
for(int j = 0; j < s.length(); j++){
A[j][j] = true;
for(int i = j - 1; i >= 0; i--){
if(i == j - 1 && s[i] == s[j]) {
A[i][j] = true;
if(longest < (j - i + 1)) {
start = i; end = j; longest = j - i + 1;
}
}
else if(i == j - 1 && s[i] != s[j]) A[i][j] = false;
else if(A[i+1][j-1] == true && s[i] == s[j]) {
A[i][j] = true;
if(longest < (j - i + 1)) {
start = i; end = j; longest = j - i + 1;
}
}
else A[i][j] = false;
}
}
res = s.substr(start, longest);
return res;
}
No comments:
Post a Comment