[LeetCode] Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

最长回文字串

回文字符串的特征就是轴对称,根据中间字符轴对称,如果字符是偶数个,那么根据中间空字符对称,如果字符是奇数个,那么根据中间字符对称。

对于长度为n的字符,这样的中心点一共有2N-1个。

从中间向两边展开,观察两边的字符是否相同。

class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.size();
        if (n == 0)
            return "";
        string res = s.substr(0, 1);
        for (int i = 0; i < n-1; ++i)
        {
            string s1 = judge(s, i, i);
            if (s1.size() > res.size())
                res = s1;
            string s2 = judge(s, i, i+1);
            if (s2.size() > res.size())
                res = s2;
        }
        return res;
    }
    
    string judge(string s, int i, int j)
    {
        while (i >= 0 && j < s.size() && s[i] == s[j])
        {
            i--;
            j++;
        }
        return s.substr(i+1, j-i-1);
    }
};

 

posted @ 2018-07-12 20:33  immjc  阅读(152)  评论(0编辑  收藏  举报