import java.util.Scanner; import java.util.Stack; // 参考:https://blog.nowcoder.net/n/6becba2a332248a4a9e5530878146159 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 String str = in.next(); System.out.println(check(str)); } static boolean check(String s) { Stack<Character> st = new Stack<>(); // 括号匹配问题 : ab[()]cd // [ or ( 入栈 // 遍历字符序列,如果当前为] 或 ) // 弹出栈顶元素,如果栈顶不为 [ 或 (,则括号配对失败;如果是,继续 // 遍历结束,检查栈中是否还有元素,如果有,匹配失败,没有,则匹配成功 for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(' || c == '[') { st.push(c); } else if (c == ']') { if (st.empty() || st.peek() != '[') { return false; } st.pop(); } else if (c == ')') { if (st.empty() || st.peek() != '(') { return false; } st.pop(); } } return st.empty(); } }