LeetCode 20:有效的括号 Valid Parentheses
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
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.
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
解题思路:
很简单的题,将字符串每个字符压入栈,简单判断即可。如:
输入: "{[]}"
初始栈为空,'{' 入栈
下一个字符
栈顶元素 '{'与 '[' 不匹配,'[' 入栈
下一个字符
栈顶元素 '['与 ']' 匹配,'[' 出栈
下一个字符
栈顶元素 '{'与 '}' 匹配,'}' 出栈
结束,栈为空,返回 True
关键在于判断字符是否匹配,匹配的标准是相反的括号字符,并非相同字符。可以用 switch 判断三种括号字符,或者三个 if 语句,再或者可以用散列表映射括号关系。
Java:
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();//初始化栈
for (char b : s.toCharArray()) {
switch (b) {
case '(': {
stack.push(')');
break;
}
case '{': {
stack.push('}');
break;
}
case '[': {
stack.push(']');
break;
}
default: {//不匹配的情况返回false
if (stack.isEmpty() || stack.pop() != b) {
return false;
}
}
}
}
return stack.isEmpty();//栈为空则证明全部匹配,返回true,否则返回false
}
}
Python:
注:python中没有 switch...case... 语句,官方让用 if 判断代替...
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for c in s:
if c == '[':
stack.append(']')
elif c == '(':
stack.append(')')
elif c == '{':
stack.append('}')
elif len(stack) == 0 or stack.pop() != c:
return False
return len(stack) == 0
欢迎关注微信公.众号:爱写Bug
LeetCode 20:有效的括号 Valid Parentheses的更多相关文章
- LeetCode 20. 有效的括号(Valid Parentheses)
20. 有效的括号 20. Valid Parentheses 题目描述 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须 ...
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...
- leetcode第31题--Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- leetcode解题报告 32. Longest Valid Parentheses 用stack的解法
第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...
- LeetCode (32) Longest Valid Parentheses
题目 Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...
- Java实现 LeetCode 20 有效的括号
20. 有效的括号 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭合. 左括号必须以正确的顺序闭合. ...
- LeetCode 20. 有效的括号(Valid Parentheses )
题目描述 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭合. 左括号必须以正确的顺序闭合. 注意空字 ...
- LeetCode第[20]题(Java):Valid Parentheses
题目:有效的括号序列 难度:Easy 题目内容: Given a string containing just the characters '(', ')', '{', '}', '[' and ' ...
- [Swift]LeetCode20. 有效的括号 | Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
随机推荐
- 前端之jquery1
jquery介绍 jQuery是目前使用最广泛的javascript函数库.据统计,全世界排名前100万的网站,有46%使用jQuery,远远超过其他库.微软公司甚至把jQuery作为他们的官方库. ...
- 用python执行Linux命令
例1:在python中包装ls命令 #!/usr/bin/env python #python wapper for the ls command import subprocess subproce ...
- VUE基础实用技巧
Vue以前听说过,有了解过一点.当时还在热衷于原生JavaScript去写一些方法的封装,不是为啥,就感觉这样很帅,后面多多少少接触了一些JQuery的用法,到现在为止,JavaScript原生封装的 ...
- Android开发总体布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...
- 一款开源且超好用的网站克隆机 HTTrack
0x00 前言 我们在学习前端的时候,总是会想着去学习其他人网站是如何制作的,或者我们遇到一些比较有用的知识点的时候,我们可能会选择通过 Ctrl + C / Ctrl + V 去扒下内容,然而我并非 ...
- [20191002]函数dump的bug.txt
[20191002]函数dump的bug.txt --//前几天写raw转化oracle number脚本,在使用函数dump时遇到一些问题,做一个记录:--//oracle number 0 编码 ...
- [20190524]浅谈模糊查询.txt
[20190524]浅谈模糊查询.txt --//一台生产系统遇到监听进程莫名down的情况,3月份曾经遇到的情况,链接:http://blog.itpub.net/267265/viewspace- ...
- nginx 文件服务器配置,模板配置文件,有注释
# For more information on configuration, see: # * Official English Documentation: http://nginx.org/e ...
- pyspark 使用时环境设置
在脚本中导入pyspark的流程 import os import sys spark_name = os.environ.get('SPARK_HOME',None) # SPARK_HOME即sp ...
- 浅谈AMD与CMD
AMD 是 RequireJS 在推广过程中对模块定义的规范化产出. CMD 是 SeaJS 在推广过程中对模块定义的规范化产出. 这些规范的目的都是为了 JavaScript 的模块化开发,特别是在 ...