5. Longest Palindromic Substring
题目链接:https://leetcode.com/problems/longest-palindromic-substring/#/description
题目大意:给定一个字符串s,返回该字符串的最长回文子串。s的最大长度不超过1000.
思路:对于每个子串的中心(可以是一个字符,或者是两个字符的间隙,比如串abc,中心可以是a,b,c,或者是ab的间隙,bc的间隙)往两边同时进行扫描,直到不是回文串为止。假设字符串的长度为n,那么中心的个数为2*n-1(字符作为中心有n个,间隙有n-1个)。
算法复杂度:对于每个中心往两边扫描的复杂度为O(n),所以时间复杂度为O(n^2),空间复杂度为O(1)
代码:
1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 if (s == "") 5 return s; 6 int start = 0, maxLen = 1; 7 for (int i = 1; i < s.size(); ++i) { 8 expandStr(s, i - 1, i, start, maxLen); 9 expandStr(s, i - 1, i + 1, start, maxLen); 10 } 11 return s.substr(start, maxLen); 12 } 13 private: 14 void expandStr(string &s, int low, int high, int &start, int &maxLen) { 15 while (low >= 0 && high < s.size() && s[low] == s[high]) { 16 --low; 17 ++high; 18 } 19 if (high - low - 1 > maxLen) { 20 start = low + 1; 21 maxLen = high - low - 1; 22 } 23 } 24 };
评测系统上运行结果:
516. Longest Palindromic Subsequence
题目链接:https://leetcode.com/problems/longest-palindromic-subsequence/#/description
题目大意:给定一个字符串s,返回该字符串的最长回文子序列。s的最大长度不超过1000.
思路:使用动态规划。longest数组记录字符串[i,j]范围的最长回文序列,动态转移方程为longest[l][r] = longest[l+1][r-1] + 2 if s[l] == s[r] else longest[l][r] = max(longest[l+1][r], longest[l][r-1]).
算法复杂度:时间复杂度为O(n^2),空间复杂度为O(n^2)
代码:
1 class Solution { 2 public: 3 int longestPalindromeSubseq(string s) { 4 if (s.empty()) 5 return 0; 6 vector<vector<int>> longest(s.size(), vector<int>(s.size())); 7 for (int len = 1; len <= s.size(); ++len) 8 for (int l = 0; l + len <= s.size(); ++l) { 9 int r = l + len - 1; 10 if (l == r) 11 longest[l][r] = 1; 12 else if (s[l] == s[r]) 13 longest[l][r] = longest[l+1][r-1] + 2; 14 else 15 longest[l][r] = max(longest[l+1][r], longest[l][r-1]); 16 } 17 return longest[0][s.size() - 1]; 18 } 19 };
评测系统上运行结果:
时间: 2024-10-11 06:07:27