[LeetCode]5 Longest Palindromic Substring(C++,Python实现),
分享于 点击 19911 次 点评:40
[LeetCode]5 Longest Palindromic Substring(C++,Python实现),
LeetCode OJ的第五题,如果有问题或者给我指点欢迎来信讨论ms08.shiroh@gmail.com
题目描述
Given a string S, find the longest palindromic substring in S. You may assume thatthe maximum length of S is 1000, and there exists one unique longest palindromic substring.
寻找一个字符串的最大回文子串
思路
最简单直观的想法就是一个一个子串试过去是否为回文。但是这样的时间复杂度很高。而且其实有很多不必判断的过程,如i到j之间,如果i-1与j-1已经不相同了,那么判断i,j毫无意义。所以很简单的思路是判断每个点扩展的最大串。遇到相同的字母相连的情况可以合在一起判断。这种方法在最坏的情况下复杂度会达到O(n^2)。 有大神给出了O(n)时间复杂度的算法,具体可以看http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html代码
Python O(n^2)class Solution:
# @return a string
def longestPalindrome(self, s):
if not s or len(s) == 1:
return s
# record the result value
max_length = 1
start_index = 0
end_index = 0
for i in range(0, len(s)-1):
count = 1
# aba
if s[i] != s[i+1]:
while i-count >= 0 and i + count < len(s) and s[i-count] == s[i+count]:
count += 1
if (count-1) * 2 + 1 > max_length:
max_length = (count-1) * 2 + 1
start_index = i - count + 1
end_index = i + count - 1
# xaaaaax
else:
count_repeat = 1
count = 0
while i+1 < len(s) and s[i] == s[i+1]:
i += 1
count_repeat += 1
while i-count_repeat+1-count >= 0 and i + count < len(s) and s[i-count_repeat+1-count] == s[i+count]:
count += 1
if (count-1) * 2 + count_repeat > max_length:
max_length = (count-1) * 2 + count_repeat
start_index = i - count -count_repeat + 2
end_index = i + count - 1
return s[start_index:end_index+1]
C++ O(n^2)
class Solution {
public:
string longestPalindrome(string s) {
if (s == "" || s.size() == 1)
return s;
// 记录结果
int max_length = 0, start_index = 0;
for (int i = 0; i < s.size()-1; ++i){
int count = 1;
// 形如aba的回文
if (s[i] != s[i+1]){
while (i-count >= 0 && i+count < s.size() && s[i-count] ==s[i+count])
++count;
if ((count-1) * 2 + 1 > max_length){
max_length = (count-1) * 2 + 1;
start_index = i - count + 1;
}
} else { // 形如xaaaaax这样的回文
int count_repeat = 0;
count = 0;
while (i+1 < s.size() && s[i] == s[i+1]){
++i;
++count_repeat;
}
while (i-count_repeat-count >= 0 && i+count < s.size() && s[i-count_repeat-count] ==s[i+count])
++count;
if ((count-1) * 2 + 1 + count_repeat > max_length){
max_length = (count-1) * 2 + 1 + count_repeat;
start_index = i - count + 1 - count_repeat;
}
}
}
return s.substr(start_index, max_length);
}
};
相关文章
- 暂无相关文章
用户点评