[LeetCode #5] Longest Palindromic Substring

Posted

tags:

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

 1 class Solution {
 2 public:
 3     string longestPalindrome(string s) {
 4         int n = s.size();
 5         if (n <= 1) return s;
 6         
 7         int start = 0;
 8         int maxlen = 0;
 9         bool ispal[1000][1000] = {false};
10         
11         for (int i = 0; i < n; i++){
12             for (int j = i; j >= 0; j--){
13                 if (s[i] == s[j] && (ispal[j+1][i-1] || j+1 > i-1)){
14                     ispal[j][i] = true;
15                     if (i - j + 1 > maxlen){
16                         maxlen = i - j + 1;
17                         start = j;
18                     }
19                 }
20             }
21         }
22         
23         return s.substr(start, maxlen);
24     }
25 };

 

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

leetcode--5. Longest Palindromic Substring

#Leetcode# 5. Longest Palindromic Substring

LeetCode题解 #5 Longest Palindromic Substring

[LeetCode] 5 Longest Palindromic Substring

Leetcode #5. Longest Palindromic Substring

LeetCode 5_Longest Palindromic Substring