0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Valid Parentheses_JS

Last updated at Posted at 2020-04-01

20200401
leetcode練習
第一問:
テーマ:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

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

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

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true
示例 2:

输入: "()[]{}"
输出: true
示例 3:

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

输入: "{[]}"
输出: true

题目解析
这道题让我们验证输入的字符串是否为括号字符串,包括大括号,中括号和小括号。

这里我们使用栈。

遍历输入字符串
如果当前字符为左半边括号时,则将其压入栈中
如果遇到右半边括号时,分类讨论:
1)如栈不为空且为对应的左半边括号,则取出栈顶元素,继续循环
2)若此时栈为空,则直接返回false
3)若不为对应的左半边括号,反之返回false

答え:
Javascript Code:

/**
* @param {string} s
* @return {boolean}
*/

var isValid = function(s) {
let valid = true;
const stack = [];
const mapper = {
    '{': "}",
    "[": "]",
    "(": ")"
}

for(let i in s) {
    const v = s[i];
    //如果遍历中的元素中包含下面三个左侧符号,放入栈中
    if (['(', '[', '{'].indexOf(v) > -1) {
        stack.push(v);
    } else {
        //取栈中最后一个元素
        const peak = stack.pop();
        //遍历元素与栈中最后一个元素进行配对,判断是否为对应的括号
        if (v !== mapper[peak]) {
            return false;
        }
    }
}
//如果配对正常stack会因为pop函数的存在而变为空,如果不为空,说明配对出现偏差,返回false
if (stack.length > 0) return false;

return valid;
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?