import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String a = in.nextLine(); Deque<Character> deque = new LinkedList<Character>(); Stack<Character> stack = new Stack<Character>(); for(int i = 0;i<a.length();i++){ if(a.charAt(i)=='['){ stack.add('['); deque.addLast('['); }else{ if(!stack.isEmpty()){ stack.pop(); deque.addLast(']'); }else{ deque.addFirst('['); deque.addLast(']'); } } } int len1 = deque.size(); for(int i = 0;i<len1;i++) System.out.print(deque.pollFirst()); int len = stack.size(); for(int i = 0;i<len;i++) System.out.print(']'); } } }
用双向队列存答案,stack存左括号匹配即可。