您的位置:首页 > 其它

[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.

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). 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: