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.
思路:(beat 2.63%)
以一个位置为准,考察两侧相同距离是否相同。这样会导致"aaaaaaaaaaaaaaaaaaaaaaaaaa..."达到最坏O(n2)的时间复杂度。
而且这种情况下需要对两种回文类型分开提取。
代码 C++:
class Solution { public: string longestPalindrome(string s) { if (s.length() <= 1) return s; string solve = ""; for (int flag = 0; flag < s.length() - solve.length() / 2; flag++) { string temp = ""; temp.push_back(s[flag]); for (int i = flag - 1,j = flag + 1; i >=0 && j < s.length() && s[i] == s[j]; i--,j++) { string ins = ""; ins.push_back(s[i]); temp.insert(0, ins); temp.push_back(s[i]); } if (temp.length() > solve.length()) solve = temp; } for (int flag = 0; flag < s.length() - solve.length() / 2; flag++) { string temp = ""; for (int i = flag,j = flag + 1; i >=0 && j < s.length() && s[i] == s[j]; i--,j++) { string ins = ""; ins.push_back(s[i]); temp.insert(0, ins); temp.push_back(s[i]); } if (temp.length() > solve.length()) solve = temp; } return solve; } };
Reference: https://leetcode.com/discuss/32204/simple-c-solution-8ms-13-lines
思路:
用i遍历字符串,j,k初始化与i相等,k++ if 相等,这样,j,k就把中奖相同的给框住了,然后再j--k++找到相同,用min_pos记录回文串首位置,max_length记录回文串长度,即j-k+1。
Θ(1)存储空间,将两种回文串一同解决,且没有上述O(n2)的最坏情况
代码:
string longestPalindrome(string s) { if (s.empty()) return ""; if (s.size() == 1) return s; int min_start = 0, max_len = 1; for (int i = 0; i < s.size();) { if (s.size() - i <= max_len / 2) break; int j = i, k = i; while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters. i = k+1; while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand. int new_len = k - j + 1; if (new_len > max_len) { min_start = j; max_len = new_len; } } return s.substr(min_start, max_len); }
时间: 2024-10-27 04:07:28