Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

20. Valid Parentheses #298

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

20. Valid Parentheses

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

Example 1

Input: "()"
Output: true

Example 2

Input: "()[]{}"
Output: true

Example 3

Input: "(]"
Output: false

Example 4

Input: "([)]"
Output: false

Example 5

Input: "{[]}"
Output: true
Tcdian commented 3 years ago

Solution

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    const stack = [];
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '(' || s[i] === '[' || s[i] === '{') {
            stack.push(s[i]);
            continue;
        }
        const part = stack.pop();
        if (
            part === '(' && s[i] === ')'
                || part === '[' && s[i] === ']'
                || part === '{' && s[i] === '}'
        ) {
            continue;
        }
        return false;
    }
    return stack.length === 0;
};
function isValid(s: string): boolean {
    const stack: string[] = [];
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '(' || s[i] === '[' || s[i] === '{') {
            stack.push(s[i]);
            continue;
        }
        const part = stack.pop();
        if (
            part === '(' && s[i] === ')'
                || part === '[' && s[i] === ']'
                || part === '{' && s[i] === '}'
        ) {
            continue;
        }
        return false;
    }
    return stack.length === 0;
};