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. 有效的括号 #4

Open
bazinga-web opened this issue Jun 3, 2020 · 2 comments
Open

✅20. 有效的括号 #4

bazinga-web opened this issue Jun 3, 2020 · 2 comments

Comments

@bazinga-web
Copy link

20. 有效的括号

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

有效字符串需满足:

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

示例 1:

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

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

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

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

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

@bazinga-web
Copy link
Author

解题思路:

  1. 创建一个 HashMap,把括号匹配进去。
  2. 创建一个 stack,循环遍历字符串,对于每一个字符,如果map有这个key,那说明
    它是个左括号,从map里取得相应的右括号push进stack中。否则它是个右括号,
    需要pop出stack里第一个字符然后看看它是否等于当前的字符,如果不相符返回 false
  3. 循环结束后,检查stack是否为空,如果不为空,说明还剩下一些左括号没有闭合,返回 false
    否则返回true
var isValid = function (s) {
  let map = new Map(),
    stack = [];
  map.set("(", ")");
  map.set("[", "]");
  map.set("{", "}");

  for (let i = 0; i < s.length; i++) {
    let item = s[i];
    if (map.has(item)) {
      stack.push(map.get(item));
    } else {
      if (stack.pop() !== item) return false;
    }
  }

  if (stack.length > 0) return false;
  return true;
};

@Ray-56
Copy link
Owner

Ray-56 commented Jun 4, 2020

stack

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
	const dict = {
		'(': ')',
		'[': ']',
		'{': '}',
	};
	const stack = [];
	for (let i = 0; i < s.length; i++) {
		if (dict[s[i]]) { // 存在 入栈
			stack.push(s[i]); 
		} else {
			// 不存在 出栈,判断与 dict key 是否一致
			if (s[i] !== dict[stack.pop()]) return false;
		}
	}
	
	return !stack.length;
}

@Ray-56 Ray-56 changed the title 20. 有效的括号 ✅20. 有效的括号 Jun 4, 2020
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

2 participants