Longest Palindrome Substring

Posted amazingzoe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Longest Palindrome 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.

 

Analyse: Consider every index i in the string. Since there are two possibilities of a palindrome: odd size or even size. If i is in the right middle of a palindrome (odd size), expand the substring starting at i towards left and right part (i - 1 && i + 1, i - 2 && i + 2...), update the result; If i and its neighbor are in the right middle of a palindrome(even size), we only consider its right neighbor because the left neighbor of i‘s right neighbor is i! Expand i and i + 1 towards left and right part (i - 1 && i + 1 + 1, i - 2 && i + 1 + 2, i - 3 && i + 1 + 3...), and update result. Be aware of that all index should be [0, s.size() - 1].

 1 class Solution {
 2 public:
 3     string longestPalindrome(string s) {
 4         string result;
 5         for (int i = 0; i < s.size(); i++) {
 6             // i is in the right middle
 7             int start = i, end = i;
 8             while(start >= 0 && end < s.size() && s[start] == s[end]) {
 9                 start--;
10                 end++;
11             }
12             result = end - start - 1 < result.size() ? result : s.substr(start + 1, end - start - 1);
13             
14             // i and i + 1 is in the right middle
15             start = i, end = i + 1;
16             while(start >= 0 && end < s.size() && s[start] == s[end]) {
17                 start--;
18                 end++;
19             }
20             result = end - start - 1 < result.size() ? result : s.substr(start + 1, end - start - 1);
21         }
22         return result;
23     }
24 };

 

以上是关于Longest Palindrome Substring的主要内容,如果未能解决你的问题,请参考以下文章

longest-palindrome

409. Longest Palindrome

Leetcode: Longest Palindrome

LeetCode 409 Longest Palindrome

[leetcode-409-Longest Palindrome]

LeetCode——409. Longest Palindrome