Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

20. Valid Parentheses #298

Open
Tcdian opened this issue Aug 14, 2020 · 1 comment
Open

20. Valid Parentheses #298

Tcdian opened this issue Aug 14, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Aug 14, 2020

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
Copy link
Owner Author

Tcdian commented Aug 14, 2020

Solution

  • JavaScript 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;
};
  • TypeScript Solution
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;
};

@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant