125.Valid Palindrome

Tags: [palindrome], [two_pointer]

Com: {fb}

Link: https://leetcode.com/problems/valid-palindrome/\#/description

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama"is a palindrome.
"race a car"isnota palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.


Solution: Two Pointer

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s:
            return True

        s = s.lower()
        left = 0
        right = len(s) - 1

        while left < right:
            while not self.is_valid(s[left]) and left < right:
                left += 1
            while not self.is_valid(s[right]) and left < right:
                right -= 1

            if left > right:
                break

            if s[left] != s[right]:
                return False
            else:
                left += 1
                right -= 1

        return True

    def is_valid(self, c):
        return '0' <= c <= '9' or 'a' <= c <= 'z'

Revelation:

  • if left > right, we can just break the loop.

Note:

  • Time complexity = O(n), n is the length of the given string.

results matching ""

    No results matching ""