LeetCode Notes_#20 Valid Parentheses
LeetCode Notes_#20 Valid Parentheses
Contents
题目
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.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
思路和解答
思路
判断一个字符串的括号的闭合规则是否是正确的,包括:
- 括号的类型要正确
- 括号闭合的顺序要正确
遍历一遍,按顺序地,分别地,把左括号都取出来,右括号都取出来,分别是一个list,然后看两个列表的对应元素是否配对。- 首先list的长度必须相同
- 然后逐一比较是否是配对的
- 遇到不配对,直接返回false;遍历到最后没有发现不配对,那么就是true。
漏洞:()[{(})]
所以需要考虑序号的因素....
还是去看了一下题解,是使用栈来做的
- 遍历整个字符串,遇到左括号就入栈
- 遇到右括号,先看栈是否为空,如果是直接返回false;否则就看跟栈中的左括号可不可以配对,不可以返回false。一轮循环后没有返回的话,说明左右括号配对,就弹出左括号。
- 最后看栈中是否为空,如果为空那么返回true(如果非空说明有左括号剩下找不到配对的右括号)
解答
Python
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack=[]
leftParen=['(','[','{']
rightParen=[')',']','}']
for i in range(len(s)):
if s[i] in leftParen:
stack.append(s[i])
else:
if stack==[]:
return False
else:
if stack[-1]=='(' and s[i]!=')':
return False
if stack[-1]=='[' and s[i]!=']':
return False
if stack[-1]=='{' and s[i]!='}':
return False
stack.pop()
return stack==[]
Java
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
HashMap<Character, Character> map = new HashMap<>();
map.put(')','(');
map.put('}','{');
map.put(']','[');
for(char c:s.toCharArray()){
//遇到的字符c是右括号,那么栈顶应该是对应的左括号
if(map.containsKey(c)){
//如果栈为空或者栈顶括号与c不对应,那么返回false
if(stack.isEmpty() || map.get(c) != stack.pop()) return false;
//遇到的字符c是左括号,将其入栈
}else{
stack.push(c);
}
}
//最后栈应该为空,不为空说明最后还有左括号没有配对
return stack.isEmpty();
}
}