题解 | #完成括号匹配#
完成括号匹配
https://www.nowcoder.com/practice/fe8d6a1b88af4ba6b4dbb10972059040
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//读取输入的字符串
String str = sc.nextLine();
String strRes = str;
int len = str.length();
int cnt = 0; //记录需要补充括号的数量
for(int i=0; i<len; i++){
if(str.charAt(i)=='['){
cnt++;
}else{
cnt--;
}
//cnt小于0,说明[多,需补充]
if(cnt<0){
cnt = 0;
strRes = "[" + strRes;
}
}
//最后cnt大于0的话,其数量为[的个数,需补充等数量的]
if(cnt>0){
for(int i=0; i<cnt; i++){
strRes += "]";
}
}
System.out.println((strRes));
}
}
查看15道真题和解析