LeetCode 125. Valid Palindrome

2019-04-09  本文已影响0人  cb_guo

题目描述

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

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

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

题目思路

class Solution {
public:
    bool isPalindrome(string s) {
        int i = 0;
        int j = s.size() - 1;
        
        while( i < j ){
            while(i < j && ! fab(s[i])) i += 1;
                
            while(i < j && ! fab(s[j])) j -= 1;
            
            if(core(s[i], s[j])){
                i += 1;
                j -= 1;
            }
            else{
                return false;
            }
        }
        return true;
    }
    
    bool fab(char c){
        if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ){
            return true;
        }
        return false;
    }
    
    bool core(char a, char b){
        if(a == b) return true;
        // a 小写字母
        if(a >= 'a' && a <= 'z'){
            if(a -32 == b){
                return true;
            }
        }
        
        // a 大写字母
        if(a >= 'A' && a <= 'Z'){
            if(a +32 == b){
                return true;
            }
        }
        return false;
    }
};

总结展望

上一篇下一篇

猜你喜欢

热点阅读