题解 | #合法括号序列判断#
合法括号序列判断
https://www.nowcoder.com/practice/d8acfa0619814b2d98f12c071aef20d4
import java.util.*; public class Parenthesis { public boolean chkParenthesis(String A, int n) { // write code here Stack<Character> stack = new Stack<>(); for(int i = 0;i<n;i++){ char c = A.charAt(i); if(c == '('){ stack.push(c); }else if (c == ')'){ if(stack.isEmpty()){ return false; } stack.pop(); }else{ return false; } } return stack.isEmpty(); } }
利用栈先进后出。后进后出的特性解决