[勇者闯LeetCode] 125. Valid Palindrome

来源:互联网 发布:信鸽分类信息软件 编辑:程序博客网 时间:2024/05/14 14:13

[勇者闯LeetCode] 125. 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" is not a 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.

Information

  • Tags: Tow Pointers | String
  • Difficulty: Easy

Solution

使用两个指针分别从字符串的首尾开始扫描,若两个指针所指向的字母不相等则返回False,否则分别寻找下一个字母进行比较,当两个指针相遇时返回True。

Python Code

class Solution(object):    def isPalindrome(self, s):        """        :type s: str        :rtype: bool        """        left, right = 0, len(s)-1        while left < right:            while left < right and not s[left].isalnum():                left += 1            while left < right and not s[right].isalnum():                right -= 1            if s[left].lower() != s[right].lower():                return False            left += 1            right -= 1        return True
0 0
原创粉丝点击