题解 | #有效括号序列# Stack
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here int len = s.length(); Stack<Character> cstk = new Stack<>(); int idx = 0; while(idx < len){ char ch = s.charAt(idx); if(cstk.isEmpty()){ cstk.push(ch); idx++; continue; } if(cstk.peek() == '{' && ch == '}') cstk.pop(); else if(cstk.peek() == '(' && ch == ')') cstk.pop(); else if(cstk.peek() == '[' && ch == ']') cstk.pop(); else { cstk.push(ch); } idx++; } if(cstk.isEmpty()){ return true; } return false; } }
经典老题,大学必做,学习数据结构栈必做题。