
Problem
Problem description
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.
Analysis
- Dynamic programming, O(n^2)
- s[i..j] is a palindromic substring iff s[i+1..j-1] is and s[i] == s[j]
Python Implementation
- Complexity: O(n^2)
- Time limit exceeded
123456789101112131415161718192021class :def longestPalindrome(self, s):""":type s: str:rtype: str"""f = [[ False for i in range(len(s) + 1)] for i in range(len(s))]for i in range(len(s)):f[i][1] = Truef[i][0] = Trueans = 1ansi = 0lens = len(s)for L in range(2, lens+1):for i in range(0, lens + 1 - L):if (s[i] == s[i+L-1]):f[i][L] = f[i+1][L-2]if (f[i][L]):ans = Lansi = ireturn s[ansi: ansi + ans]
C++ Implementation
- Complexity: O(n^2)
- Accepted
1234567891011121314151617181920212223242526272829using namespace std;class Solution {public:string longestPalindrome(string s) {int f[1000][1005];memset(f, 0, sizeof(f));int n = s.length();for (int i = 0; i < n; i++)f[i][0] = f[i][1] = 1;int ans = 1;int ansi = 0;for (int L = 2; L <= n; L++) {for (int i = 0; i <= n - L; i++){if (s[i] == s[i + L -1])f[i][L] = f[i+1][L-2];if (f[i][L]){ans = L;ansi = i;}}}return s.substr(ansi, ans);}};




近期评论