7-lines 12ms Easy C++ Solution


  • 7

    The suggested solution to this problem has given a clear idea. The tricky part of this problem is to handle all the edge cases carefully and write a clean code.

    The following code should be self-explanatory. Note that the use of toupper avoids some messy if-else statements.

    class Solution {
    public:
        bool isPalindrome(string s) {
            int l = 0, r = s.length() - 1; 
            while (l < r) {
                while (l < r && !isalnum(s[l])) l++;
                while (r > l && !isalnum(s[r])) r--; 
                if (toupper(s[l++]) != toupper(s[r--]))
                    return false;
            }
            return true; 
        }
    };

Log in to reply
 

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