检查一段C语言代码的小括号( )、 中括号 [ ] 和大括号{ } 是否匹配。
输入格式:
在一行中输入一段C语言代码,长度不超过1000个字符(行末以换行符结束)。
输出格式:
第一行输出左括号的数量和右括号的数量,中间以一个空格间隔。
若括号是匹配的,在第二行打印YES,否则打印NO。
输入样例1:
for(int i=0; i<v; i++){ visited[i] = 0; for(int j=0; j<v; j++) scanf("%d",&(g->Adj[i][j])); }
输出样例1:
8 8 YES
输入样例2:
for(int i=0; i<v; i++) a(i]=0;
输出样例2:
2 2 NO思路: 注意两点:如果没有右括号与之匹配,不要break,要继续统计括号的数量;满足左括号都有右括号与之匹配,这时候可能有多余的左括号,因此不仅要判断flag=true,还要加上栈为空代码:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
Stack<Character> sta=new Stack<Character>();
Map<Character, Character> map=new HashMap<Character, Character>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
String s=scan.nextLine();
char[] a=s.toCharArray();
boolean flag=true;
int cnt1=0,cnt2=0;
for(int i=0;i<a.length;i++){
if(a[i]=='(' ||a[i]=='[' ||a[i]=='{') {
sta.push(a[i]);
cnt1++;
}
else if(a[i]==')' ||a[i]==']' ||a[i]=='}'){
cnt2++;
if(!sta.isEmpty() && map.get(sta.peek())==a[i]){
sta.pop();
}
else{
flag=false;//不要break,因为需要继续统计数量
}
}
}
System.out.println(cnt1+" "+cnt2);
if(flag && sta.isEmpty()) System.out.println("YES");//判栈空
else System.out.println("NO");
}
}
来源:https://www.cnblogs.com/qdu-lkc/p/12207205.html