125. 验证回文串


  • 思路很简单,两个指针,一个从前向后遍历,一个从后向前遍历,直到两个指针相遇。如果中间出现两个值不相同的情况,说明不是回文串。

  • Python

    class Solution:
        def isPalindrome(self, s: str) -> bool:
            if s == "":
                return True
            
            ptr1 = 0
            ptr2 = len(s)-1
            while ptr1 < ptr2:
                
                if not s[ptr1].isalnum():
                    ptr1 += 1
                elif not s[ptr2].isalnum():
                    ptr2 -= 1            
                elif s[ptr1].lower() != s[ptr2].lower():
                    return False
                else:
                    ptr1 += 1
                    ptr2 -= 1
                
            return True
    
  • Go

    func isalnum(s byte) bool{
        if 'a'<= s && s <= 'z'{
            return true
        }else if 'A' <= s && s <= 'Z'{
            return true
        }else if '0' <= s && s <= '9' {
            return true
        }else{
            return false
        }
    }
    func isPalindrome(s string) bool {
        if s == ""{
            return true
        }
        ptr1 := 0
        ptr2 := len(s)-1
        
        for ;ptr1<ptr2;{
            if ! isalnum(s[ptr1]){
                ptr1++
            }else if ! isalnum(s[ptr2]){
                ptr2-- 
            }else if strings.ToLower(string(s[ptr1])) != strings.ToLower(string(s[ptr2])){
                return false
            }else{
                ptr1++
                ptr2--
            }
        }
        return true
    }
    
posted @ 2020-06-17 14:53  暮晨  阅读(226)  评论(0编辑  收藏  举报

Aaron Swartz was and will always be a hero