Neat O(n), O(1) solution with isalnum()


  • 19
    N
    class Solution {
    public:
    	bool isPalindrome(string s) {
    
    		int i = 0, j = s.size() - 1;
    		while(i < j)
    		{
    			while(i < j && !isalnum(s[i])) i++;
    			while(i < j && !isalnum(s[j])) j--;
    			if (toupper(s[i])!=toupper(s[j]))
    				return false;
    			i++;j--;
    		}
    		return true;
    	}
    };

  • 0
    M

    oh nice, mine looks exactly the same except I didn't know about isalnum function, so I defined alphabet string, and did alphabet.find() == string::npos :)


  • 0
    W

    Thank you for those handy function! They make my code more elegant and compact.


Log in to reply
 

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