5. 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"

解答

分奇偶的双重循环,水题。

class Solution {
public:
    string longestPalindrome(string s) {
        int l = s.length();
        string max_subs;
        int max_len = 0;
        for (int i = 0; i < 2 * l - 1; i++) {
            int len = 0, left, right, j;
            string subs;
            // 元素为中心,子串长度为奇数
            if (i % 2 == 0) {
                int index = int(i / 2);
                for (j = 0; j <= min(index, l - 1 - index); j++) {
                    left = s[index - j];
                    right = s[index + j];
                    if (left != right) {
                        break;
                    }
                }
                j = max(j, 1);
                len = 2 * (j - 1) + 1;
                subs = s.substr(index - j + 1, len);
            }
            // 元素为中心,子串长度为偶数
            else {
                int index_left = int(i / 2), index_right = int(i / 2) + 1;
                for (j = 0; j < min(index_right, l - index_right); j++) {
                    left = s[index_left - j];
                    right = s[index_right + j];
                    if (left != right) {
                        break;
                    }
                }
                len = 2 * j;
                subs = s.substr(index_left - j + 1, len);
            }
            if (max_len < len) {
                max_len = len;
                max_subs = subs;
            }
        }
        return max_subs;
    }
};

你可能感兴趣的:(5. Longest Palindromic Substring)