题解 | #完成括号匹配#
完成括号匹配
https://www.nowcoder.com/practice/fe8d6a1b88af4ba6b4dbb10972059040
import java.util.Scanner; import java.util.Stack; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); Stack<Character> stack = new Stack<Character>(); for (char c : s.toCharArray() ) { if (c == ']' && !stack.isEmpty() && stack.peek() == '[') { stack.pop(); } else { stack.push(c); } } int l = 0; int r = 0; while (!stack.isEmpty()) { if (stack.peek() == '[') { l ++; } else r ++; stack.pop(); } for (int i = 0; i < r; i++) { System.out.print("["); } System.out.print(s); for (int i = 0; i < l; i++) { System.out.print("]"); } } }
这类符号匹配问题还是用栈进行匹配比较好使
#如何一边实习一边秋招#