20. 有效的括号

难度简单

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

有效字符串需满足:

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

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

示例 1:

输入: "()"
输出: true

示例 2:

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

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true
通过次数209,977
提交次数513,031
贡献者
LeetCode
相关企业
相关标签
显示提示1
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
{ { } [ ] [ [ [ ] ] ] } is VALID expression
          [ [ [ ] ] ]    is VALID sub-expression
  { } [ ]                is VALID sub-expression
Can we exploit this recursive structure somehow?
显示提示2
What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g.
{ { ( { } ) } }
      |_|

{ { (      ) } }
    |______|

{ {          } }
  |__________|

{                }
|________________|

VALID EXPRESSION!
显示提示3
The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
贡献
#1 两数之和
简单
#2 两数相加
中等
#3 无重复字符的最长子串
中等
#4 寻找两个有序数组的中位数
困难
#5 最长回文子串
中等
#6 Z 字形变换
中等
#7 整数反转
简单
#8 字符串转换整数 (atoi)
中等
#9 回文数
简单
#10 正则表达式匹配
困难
#11 盛最多水的容器
中等
#12 整数转罗马数字
中等
#13 罗马数字转整数
简单
#14 最长公共前缀
简单
#15 三数之和
中等
#16 最接近的三数之和
中等
#17 电话号码的字母组合
中等
#18 四数之和
中等
#19 删除链表的倒数第N个节点
中等
#20 有效的括号
简单
#21 合并两个有序链表
简单
#22 括号生成
中等
#23 合并K个排序链表
困难
#24 两两交换链表中的节点
中等
#25 K 个一组翻转链表
困难
#26 删除排序数组中的重复项
简单
#27 移除元素
简单
#28 实现 strStr()
简单
#29 两数相除
中等
#30 串联所有单词的子串
困难
#31 下一个排列
中等
#32 最长有效括号
困难
#33 搜索旋转排序数组
中等
#34 在排序数组中查找元素的第一个和最后一个位置
中等
#35 搜索插入位置
简单
#36 有效的数独
中等
#37 解数独
困难
#38 外观数列
简单
#39 组合总和
中等
#40 组合总和 II
中等
#41 缺失的第一个正数
困难
#42 接雨水
困难
#43 字符串相乘
中等
#44 通配符匹配
困难
#45 跳跃游戏 II
困难
#46 全排列
中等
#47 全排列 II
中等
#48 旋转图像
中等
#49 字母异位词分组
中等
#50 Pow(x, n)
中等