有效的括号
利用栈先进后出的特性实现
class Solution {
private HashMap<Character,Character> map;
public Solution(){
this.map = new HashMap<>();
map.put('(',')');
map.put('{','}');
map.put('[',']');
}
public boolean isValid(String s) {
Stack<Character> st = new Stack<>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
st.push(c);
}else{
if(st.empty()) return false;
char topelement = st.pop();
if(map.get(topelement) != c) return false;
}
}
return st.empty()? true : false;
}
}
运行结果:
题目来源leetcode 题库20题
来源:CSDN
作者:枝丫芝
链接:https://blog.csdn.net/qq_37143212/article/details/104201545