Skip to content

Latest commit

 

History

History
145 lines (102 loc) · 3.45 KB

File metadata and controls

145 lines (102 loc) · 3.45 KB

20. Valid Parentheses - 有效的括号

Tags - 题目标签

Description - 题目描述

EN:

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

 

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

ZH-CN:

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

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
  3. 每个右括号都有一个对应的相同类型的左括号。

 

示例 1:

输入:s = "()"
输出:true

示例 2:

输入:s = "()[]{}"
输出:true

示例 3:

输入:s = "(]"
输出:false

 

提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成

Link - 题目链接

LeetCode - LeetCode-CN

Latest Accepted Submissions - 最近一次 AC 的提交

Language Runtime Memory Submission Time
typescript 56 ms 42.7 MB 2022/05/02 13:34
function isValid(s: string): boolean {
  const stack: ('{' | '[' | '(')[] = [];

  for (let i = 0; i < s.length; i++) {
    if (s[i] === '{' || s[i] === '[' || s[i] === '(') {
      stack.push(s[i] as '{' | '[' | '(');
    } else {
      const left = stack.pop();
      if (left) {
        if (s[i] === '}') {
          if (left !== '{') {
            return false;
          }
        } else if (s[i] === ']') {
          if (left !== '[') {
            return false;
          }
        } else {
          if (left !== '(') {
            return false;
          }
        }
      } else {
        return false;
      }
    }
  }
  return stack.length === 0;
};

My Notes - 我的笔记

No notes