Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
- Input: "babad"
- Output: "bab"
- Note: "aba" is also a valid answer.
Example:
- Input: "cbbd"
- Output: "bb"
C Solution:
char* longestPalindrome(char* s) {
if (!s || !*s) return 0;
int i, res = 1, l = 0, r = 0;
for (i = 1; s[i]; i++) {
int j;
for (j = 1; j <= i && s[i + j] && s[i - j] == s[i + j]; j++);
if (2 * j - 1 > res) {
l = i - j + 1;
r = i + j - 1;
res = 2 * j - 1;
}
if (s[i - 1] == s[i]) {
for (j = 1; i - 1 - j >= 0 && s[i + j] && s[i - 1 - j] == s[i + j]; j++);
if (2 * j > res) {
l = i - j;
r = i + j - 1;
res = 2 * j;
}
}
}
char *rs = malloc(r - l + 2);
memcpy(rs, s + l, r - l + 1);
rs[r - l + 1] = 0;
return rs;
}
Python Solution:
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) < 2: return s
l = ['*']
for c in s: l.extend([c, '*'])
max_center, max_radius = 1, 1
center, left = 1, 2
d = [0] * len(l)
d[1] = 1
for cur in range(2, len(l)):
if 2 * center - cur >= 0:
radius = d[2 * center - cur]
if radius + cur < left:
d[cur] = radius
continue
radius = left - cur if left > cur else 0
while cur - radius - 1 > -1 and cur + radius + 1 < len(l) and l[cur - radius - 1] == l[cur + radius + 1]:
radius += 1
if cur + radius > left:
if radius > max_radius:
max_center = cur
max_radius = radius
center = cur
left = cur + radius
if left == len(l) - 1: break
d[cur] = radius
l = l[max_center - max_radius: max_center + max_radius + 1]
return ''.join([c for c in l if c != '*'])
Summary:
- python solution is much better.
LeetCode: 5. Longest Palindromic Substring
近期评论