在一行中输入一个字符串
,长度
,由可见字符组成。
如果字符串
中的括号部分能构成合法括号序列,则输出
;否则输出
。
abcd(])[efg
false
提取括号 `(`、`)`、`[`、`]` 后为 `(])[`,不是合法括号序列。
a[x(y)z]
true
提取括号后为 `[()]`,是合法括号序列。
import java.util.Scanner; import java.util.Stack; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.next(); System.out.print(bracketMatch(str)); } public static boolean bracketMatch(String str) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); // 如果是左括号,入栈 if (c == '(' || c == '[') { stack.push(c); } // 如果是右括号 else if (c == ')' || c == ']') { // 栈为空,没有匹配的左括号 if (stack.isEmpty()) { return false; } // 弹出栈顶元素并检查是否匹配 char top = stack.pop(); if ((c == ')' && top != '(') || (c == ']' && top != '[')) { return false; } } } // 所有括号处理完毕后,栈必须为空才是完全匹配 return stack.isEmpty(); } }
public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); Stack<Character> stack = new Stack<>(); for (int i=0;i<str.length();i++){ char c = str.charAt(i); if (c == '(' || c == '[') stack.push(c); else if (c == ')'){ if (stack.isEmpty() || stack.pop() != '(') { System.out.println(false); return; } }else if (c == ']'){ if (stack.isEmpty() || stack.pop() != '[') { System.out.println(false); return; } } } if (stack.isEmpty()) System.out.println(true); else System.out.println(false); } }