把已匹配到的方括号换成花括号,最后再换回来:
import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder r = new StringBuilder(sc.nextLine()); while(r.indexOf("]") != -1){ int j = r.indexOf("]"); r.setCharAt(j, '}'); int i = j - 1; while(i >= 0 && r.charAt(i) != '[') i--; if(i < 0) r.insert(0, '{'); else r.setCharAt(i, '{'); } int c = 0; for(int i = 0; i < r.length(); ++i){ if(r.charAt(i) == '[') c++; } for(int i = 0; i < r.length(); ++i){ if(r.charAt(i) == '{') r.setCharAt(i, '['); if(r.charAt(i) == '}') r.setCharAt(i, ']'); } while(c-- > 0) r.append("]"); System.out.println(r); } }