题解 | #有效括号序列# #Java# 简单,直觉
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
import java.util.*; public class Solution { /** * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { Stack<Character> stack = new Stack<>(); for(char c: s.toCharArray()) { if(stack.isEmpty()) { //放入第一个字符并直接跳入下一轮 stack.push(c); continue; } char top = stack.peek(); //查看堆顶是否能与当前符号匹配。若匹配,则去除堆顶 if(c == ')' && top == '(') stack.pop(); else if(c == ']' && top == '[') stack.pop(); else if(c == '}' && top == '{') stack.pop(); else stack.push(c); //不匹配,则压入 } return stack.isEmpty(); //全部匹配时,堆被清空 } }