题目链接:http://oj.leetcode.com/problems/longest-palindromic-substring/
题目描述:
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.
题目意思:找出给定字符串中最常的回文字串,输入保证有且仅有一个正确结果。
解法一:
暴力求解,时间复杂度O(n^2).提交会超时。
代码如下:
string longestPalindrome(string s) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int result = 0;
int start = -1;
int len = s.length();
if(len <= 0) return NULL;
if(len == 1) return s;
for(int i=0;i < len; ++i){
int j = i+1;
while(j < len){
if( isPalindrome(s, i, j)){
int temp = j - i + 1;
if(temp > result){
result = temp;
start = i;
}
}
j++;
}
}
return s.substr(start, result);
}
bool isPalindrome(string s, int start, int end){
while(start < end){
if(s[start++] != s[end--])
return false;
}
return true;
}
解法二:
暴力求解,时间复杂度O(n^2)。能通过,rp好吗!
思路:分别以每个位置为中心向两边扩展。
代码如下:
string longestPalindrome(string s) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int result = 0;
int start = 0;
int len = s.length();
if(len <= 0) return NULL;
if(len == 1) return s;
for(int i=0;i < len; ++i){
int f = i+1,b = i;
int temp;
while(b >=0 && f < len && s[b] == s[f])
b--, f++;
temp = f - b - 1;
if(temp > result){
result = temp;
start = b + 1;
}
f = i+1, b = i-1;
while(b >=0 && f < len && s[b] == s[f])
b--, f++;
temp = f - b - 1 ;
if(temp > result){
result = temp;
start = b + 1;
}
}
return s.substr(start, result);
}
未完待续…………DP和O(n)