力扣刷题——有效的括号

题目: https://leetcode-cn.com/problems/valid-parentheses/

1.switch case

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    let arr = []
    if(s.length % 2 !== 0) return false
    for(let i = 0; i < s.length; i++){
        let letter = s[i]
        switch(letter){
            case '(': {
                arr.push(letter)
                break
            }
            case '{': {
                arr.push(letter)
                break
            }
            case '[': {
                arr.push(letter)
                break
            }
            case ')': {
                if(arr.pop() !== '(') return false
                break
            }
            case '}': {
                if(arr.pop() !== '{') return false
                break
            }
            case ']': {
                if(arr.pop() !== '[') return false
                break
            }
        }
    }
    return !arr.length
};

2.哈希表map

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    let arr = []
    let map = {
        '(': ')',
        '{': '}',
        '[': ']'
    }
    if(s.length % 2 !== 0 ) return false
    for(let i = 0;i < s.length; i++){
        let letter = s[i]
        if(map[letter]){
            arr.push(letter)
        }
        else {
            if( map[arr.pop() ] !== letter) return false
        }
    }
    return !arr.length
};

你可能感兴趣的:(刷题)