入口
力扣https://leetcode.cn/problems/valid-parentheses/submissions/
题目描述
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()"
输出:true
示例 2:输入:s = "()[]{}"
输出:true
示例 3:输入:s = "(]"
输出:false
方法一:栈
解题思路
- 遍历字符串
- 将左括号入栈
- 如果是右字符串则进行判断
- stack是否为空 字符串全是右字符串的情况。
- 和最近的字符串匹配
- 匹配成功将左括号出栈
- 最后栈为空则代表符合规则
代码示例
class Solution {
public boolean isValid(String s) {
int n = s.length();
if(n%2==1){return false;}
Map<Character,Character> pairs = new HashMap<Character,Character>(){{
put(')','(');
put(']','[');
put('}','{');
}};
Deque<Character> stack = new LinkedList<Character>();
for(int i=0;i< n;i++){
char ch = s.charAt(i);
if(pairs.containsKey(ch)){
//前面没有左括号或者最近的左括号不匹配
if(stack.isEmpty() || stack.peek() != pairs.get(ch)){
return false;
}
if(!stack.isEmpty())stack.pop();
}else{
stack.push(ch);
}
}
return stack.isEmpty();
}
}