讨论/《数组和字符串》 - 最长回文子串/
《数组和字符串》 - 最长回文子串
pair<int, int> func(string s, int left, int right) {
    while (left >= 0 && right < s.size() && s[left] == s[right]) {
        left--;
        right++;
    }
    return make_pair(left + 1, right - 1);
}

class Solution {
public:
    string longestPalindrome(string s) {
        int start = 0, end = 0;
        for (int i = 0; i < s.size(); i++) {
            auto tmp = func(s, i, i);
            auto tmp2 = func(s, i, i + 1);
            if (tmp.second - tmp.first > end - start) {
                start = tmp.first;
                end = tmp.second;
            }
            if (tmp2.second - tmp2.first > end - start) {
                start = tmp2.first;
                end = tmp2.second;
            }
        }
        return s.substr(start, end - start + 1);
    }
};
展开全部 11 讨论