4 line c++ code using stl (modify the origin string)


  • 2
    R

    class Solution {

    public:

    bool isPalindrome(string s) {
        auto e = remove_if(s.begin(), s.end(), [](char c) { return !isalnum(c);});
    
        auto new_rend = string::reverse_iterator(e);
    
        return s.empty() || equal(s.begin(), new_rend.base(), new_rend,
                                 [](char a, char b) { return tolower(a) == tolower(b); });
    }
    

    };

    or it could be 3 line...

    class Solution {

    public:

    bool isPalindrome(string s) {
        s.erase(remove_if(s.begin(), s.end(), [](char c) { return !isalnum(c);}), s.end());
    
        return s.empty() || equal(s.begin(), s.end(), s.rbegin(),
                                 [](char a, char b) { return tolower(a) == tolower(b); });
    }
    

    };


Log in to reply
 

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