美文网首页
5 - 125. Valid Palindrome

5 - 125. Valid Palindrome

作者: bestCindy | 来源:发表于2022-06-20 11:20 被阅读0次

    https://leetcode.com/problems/valid-palindrome/

    var isPalindrome = function(s) {
        s = s.toLowerCase();
        
        let str = '';
        for (let i = 0; i <= s.length; i++) {
            if ((s[i] >= 0 && s[i] < 10) || (s[i] >= 'a' && s[i] < 'z')) {
                 (s[i] !== ' ') && (str += s[i]);
            }
        }
        
        let flag = true;
        for (let i = 0; i < (str.length - 1)/2; i++) {
            if (str[i] !== str[str.length - 1 - i]) {
                flag = false;
                break;
            }
        }
        
        return flag;
    };
    

    in the case s[i] === ' ' the expression s[i] >= 0 returns true, so we need to filter it with expression s[i] !== ' '

    another better approach

    var isPalindrome = function(s) {
        let start = 0;
        let end = s.length - 1;
        
        while (start <= end) {
            let left = s.charCodeAt(start);
            let right = s.charCodeAt(end);
            
            if (!isLetter(left)) {
                start++;
                continue;
            }
            
            if (!isLetter(right)) {
                end--;
                continue;
            }
            
            if (toLowerCase(left) !== toLowerCase(right)) {
                return false;
            }
            
            start++;
            end--;
        }
        
        return true;
    };
    
    function isLetter(code) {
        if (((code >= 48) && (code <= 57))
        || ((code >= 65) && (code <= 90))
        || ((code >= 97) && (code <= 122))) {
            return true;
        }
        
        return false;
    }
    
    function toLowerCase(code) {
        if (code >= 65 && code <= 90) {
            return code + 32
        }
        
        return code;
    }
    

    I forgot to increase start and decrease end during each execute in the loop in the first time I submitted the code which leads to time limit exceeded

    Don't forget to check if the code causes an infinite loop

    we can use regex to remove non-alphanumeric

    s = s.replace(/[^A-Za-z0-9]/g, '')
    

    and we can use Array.every to instead of while

    first convert string

    let string = s.toLowerCase().replace(/[^a-z0-9]/g, "");
    

    then filter the string

    return string.split('').slice(0, Math.floor(string.length / 2)).every((letter, index) => letter === string[string.length - 1 - index])
    

    相关文章

      网友评论

          本文标题:5 - 125. Valid Palindrome

          本文链接:https://www.haomeiwen.com/subject/xvddvrtx.html