20. 有效的括号
地址: https://leetcode-cn.com/problems/valid-parentheses/
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路: 利用堆栈,后进先出的方式来匹配。
最上面的如果能匹配就去掉,如果不能就放入堆栈
Python代码:
class Solution:
def isValid(self, s: str) -> bool:
dic={")":"(","}":"{","]":"["}
stack = []
for i in s:
if i in dic:
if len(stack)>0:
if dic[i]==stack[-1]:
stack.pop()
else:
stack.append(i)
else:
stack.append(i)
else:
stack.append(i)
if len(stack)==0:
return True
else:
return False
Scala代码:
object Solution {
def isValid(s: String): Boolean = {
val dic = Map(")"->"(","}"->"{","]"->"[")
stack = List()
var i=null
for ( i <- s ){
if (dic.contains(i)){
if (stack.length>0){
if (stack(0)==dic[i]){
stack = stack.tail
}else{
stack = i :+ stack
}
}else{
stack = i :+ stack
}
}else{
stack = i :+ stack
}
}
if (stak.length==0){
return True
}else{
return False
}
}
}