clueless coding // TODO: be smarter

LeetCode Longest Palindromic Substring: CPP Solution



TL;DR Code Solution


string longestPalindrome(string s) {
    string result;
    int maxLen = 0;
    int low = INT_MIN;
    for (int i = 0; i < s.length(); i++) {
        findPalindromes(s, i, i, result, maxLen, low);    
    }
    for (int i = 1; i < s.length(); i++) {
        findPalindromes(s, i, i - 1, result, maxLen, low);
    }

    return s.substr(low, maxLen);
}

void findPalindromes(string s, int i, int j, string& result, int& maxLen, int& low) {
    string cur;
    int curLen = 0;
    while (i >= 0 && j < s.length() && s[i] == s[j]) {
        i++;
        j--;
    }

    if (i - j - 1 > maxLen) {
        maxLen = i - j - 1;
        low = j + 1;
    }
}