Palindrome String Check With Non-alphanumeric Characters

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) < 1:
            return True
        
        start, end = 0, len(s) - 1
        
        while start < end:
            # Loop till a special char is found
            while start < end and not s[start].isalnum():
                start += 1
                
            # Always keep the check start < end
            while start < end and not s[end].isalnum():
                end -= 1
            
            # For a pure non-alnum string e.g. "..", start = end = 1
            # The next iteration will have start +=1 => 2
            # So breaking the loop correctly.
            
            if s[start].lower() != s[end].lower():
                return False
            
            start += 1
            end -= 1
            
        return True

Reference

Written with StackEdit.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.