8ms C++ solution, easy to understand


  • 3
    M
    string longestPalindrome(string s) {
            if(s.size() < 2) return s;
            std::map<int,int> mpal;//<len,start> 
            for(int i=0; i<s.size();)
            {
                int start = i;
                while(s[start] == s[i+1]) ++i;
                int finish = i;
                while(start >= 0 && finish < s.size() && s[start] == s[finish]) 
                {
                    --start;
                    ++finish;
                }
                if(finish - start >= 3) mpal.insert(std::make_pair(finish-start-1, start+1));
                ++i;
            }
            auto m = std::max_element(mpal.begin(),mpal.end());
            return s.substr((*m).second,(*m).first);
        }

  • 0
    Y

    Expand from the middle of the substr, nice solution.


  • 0
    X

    good gun,your C++ is fantastic


  • 0

    good. But actually "while(s[start] == s[i+1]) ++i;" will go wrong if the string is like: "qqqqq". Because you do not check s[i+1] is valid or not


Log in to reply
 

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