One C++ solution


  • 0
    D
    class Solution {
    public:
        bool isPalindrome(const string& s, size_t b, size_t e) {
            for(size_t i = b, j = e; i < j; i++, j--) {
                if (s[i] != s[j]) return false;
            }
            return true;
        }
        
        string longestPalindrome(string s) {
            int n = s.length();
            size_t index = string::npos;
            int longestLen = 0;
            for (int i = 0; i < n; i++) {
                int nextPos = n;
                while(string::npos != (nextPos = s.find_last_of(&s[i], nextPos - 1, nextPos - i))
                      && (nextPos + 1 - i) > longestLen) {
                    if(isPalindrome(s, i, nextPos)) {
                        index = i;
                        longestLen = nextPos + 1 - index;
                        break;  // first matched would be the longest one for current i
                    }
                }
            }
            return (string::npos != index) ? s.substr(index, longestLen) : "";
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.