程式語言 - LeetCode - C++ - 5. Longest Palindromic Substring



參考資訊:
https://www.cnblogs.com/grandyang/p/4464476.html
https://neetcode.io/solutions/longest-palindromic-substring

題目:


解答:

class Solution {
public:
    string longestPalindrome(string s) {
        int len = 0;
        string res = "";

        for (int i = 0; i < s.size(); ++i) {
            for (int j = 0; j < s.size(); ++j) {
                int l = i;
                int r = j;

                while ((l < r) && (s[l] == s[r])) {
                    l += 1;
                    r -= 1;
                }

                if ((l >= r) && (len < (j - i + 1))) {
                    res = s.substr(i, j - i + 1);
                    len = j - i + 1;
                }
            }
        }

        return res;
    }
};