hot100
1.有效的括号
题目:给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true
class Solution {
HashMap<Character,Character> mapping;
public Solution(){
this.mapping = new HashMap();
mapping.put(')','(');
mapping.put(']','[');
mapping.put('}','{');
}
public boolean isValid(String s) {
Stack<Character> result = new Stack();
for(int i=0;i<s.length();i++){
char first = s.charAt(i);
if(mapping.containsKey(first)){
char staChar = result.isEmpty()?'#':result.pop();
if(staChar!=mapping.get(first)){
return false;
}
}else{
result.push(first);
}
}
return result.isEmpty();
}
}
主要是用栈解决问题,将一边的括号压栈,然后解决最近的一对括号,然后弹栈,最后栈的长度是0就对了,不是0或者中间过程的最近一对括号没有对上,就是格式错误,返回false.
来源:CSDN
作者:千雨猫
链接:https://blog.csdn.net/qq_33598343/article/details/103981337