Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 5. Longest Palindromic Substring

Rain Hu

5. Longest Substring Without Repeating Characters


一、題目

Given a string s, return the longest palindromic substring in s.
A string is called a palindrome string if the reverse of that string is the same of the original string.

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. Dynamic Prograimming

string longestPalindrome(string s) {
    int n = s.length();
    string res;
    bool dp[n][n];
    memset(dp, false, sizeof(dp));
    int len = 0;
    for (int j = 0; j < n; j++) {
        for (int i = 0; i <= j; i++) {
            if (i == j) {   // 長度為 1
                dp[i][j] = true;
            } else if (j - i == 1) {    // 長度為 2
                dp[i][j] = s[i] == s[j];
            } else {        // 長度 > 2
                dp[i][j] = s[i] == s[j] && dp[i+1][j-1];
            }

            if (dp[i][j] && j - i + 1 > len) {    // 比較長度
                len = j - i + 1;
                res = s.substr(i, len);
            }
        }
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[Leetcode] 6. Zigzag Conversion
Next
[LeetCode] 4. Median of Two Sorted Arrays