Simple and Easy to Understand C++ 103 ms solution


  • 1
    D
    class Solution {
    public:
        string longestPalindrome(string s) {
            if(s.length() <= 1) return s;
            int i, max = 1;
            string longestPalindrome, currentPalindrome;
            for(i=0;i<s.length();i++)
            {
                currentPalindrome = s[i];
                int backward = i - 1;
                int forward = i + 1;
                int count = 1;
                while(forward < s.length() && s[forward] == s[i])
                {
                    currentPalindrome = currentPalindrome + s[forward];
                    count++;
                    i = forward;
                    forward++;
                }
                while(backward >=0 && forward < s.length() && s[backward] == s[forward])
                {
                    currentPalindrome = s[backward] + currentPalindrome + s[forward];
                    backward--;
                    forward++;
                    count += 2;
                }
                if(count > max){ 
                    max = count;
                    longestPalindrome = currentPalindrome;
                }
            }
            return longestPalindrome;
        }
    };
    

Log in to reply
 

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