[Leetcode] Longest Palindromic Substring
2014-11-10 04:41
393 查看
题目:
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.
思路:经典的回文问题,中心扩展,考虑奇偶两种情况。O(n)算法见 http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html.
总结:每个字符作为中心展开,展开过程中最多访问n个字符,复杂度为O(n^2).
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.
思路:经典的回文问题,中心扩展,考虑奇偶两种情况。O(n)算法见 http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html.
class Solution { public: string longestPalindrome(string s) { int max_len = INT_MIN; string result = ""; for (int i = 0; i < (int)s.size(); ++i) { // odd length for (int j = 0; i - j >= 0 && i + j < (int)s.size(); ++j) { if (s[i-j] != s[i+j]) break; if (j * 2 + 1 > max_len) { //update max_len = j * 2 + 1; result = s.substr(i - j, j * 2 + 1); } } // even length for (int j = 0; i - j >= 0 && i + 1 + j < (int)s.size(); ++j) { if (s[i-j] != s[i+1+j]) break; if (j * 2 + 2 > max_len) { //update max_len = j * 2 + 2; result = s.substr(i - j, j * 2 + 2); } } } return result; } };
总结:每个字符作为中心展开,展开过程中最多访问n个字符,复杂度为O(n^2).
相关文章推荐
- leetcode:Longest Palindromic Substring
- [Leetcode]Longest Palindromic Substring
- [LeetCode] Longest Palindromic Substring
- LeetCode 5. Longest Palindromic Substring
- [leetcode 5] Longest Palindromic Substring
- 【Leetcode】5. Longest Palindromic Substring
- [LeetCode] Longest Palindromic Substring
- LeetCode: Longest Palindromic Substring
- [leetcode]Longest Palindromic Substring
- #leetcode#Longest Palindromic Substring
- leetcode 第5题 Longest Palindromic Substring
- Leetcode_005_Longest_Palindromic_Substring
- LeetCode5-Longest Palindromic Substring
- *LeetCode-Longest Palindromic Substring
- 【LeetCode】Longest Palindromic Substring 解题报告
- leetcode 5 :Longest Palindromic Substring 找出最长回文子串
- LeetCode Longest Palindromic Substring
- LeetCode 5 Longest Palindromic Substring
- leetcode 5—— Longest Palindromic Substring
- leetcode 5 -- Longest Palindromic Substring