新华三:括号匹配

题目:

有表达式:(x+y)*(x-y),验证是否括号匹配,如果括号匹配请输出其括号嵌套深度

 

Java:

 1 import java.util.Scanner;
 2 import java.util.Stack;
 3 
 4 public class Main {
 5     
 6     public static void main(String[] args) {
 7         Scanner sc=new Scanner(System.in);
 8         while(sc.hasNext()){
 9             String s = sc.nextLine();
10             Stack<Character> st = new Stack<Character>();
11             int num = 0;
12             int count = 0;
13             int i = 0;
14             for(; i < s.length(); i++){
15                 switch (s.charAt(i)) {
16                 case '(':
17                     st.push(s.charAt(i));
18                     count++;
19                     if(count > num){
20                         num = count;
21                     }
22                     break;
23                 case ')':
24                     if(!st.isEmpty()){
25                         st.pop();
26                         count--;
27                     }
28                     else{
29                         i = s.length();
30                     }
31                     break;
32                     
33                 default:
34                     break;
35                 }
36             }
37             
38             if((count == 0)&&(i==s.length())){    //现场笔试,少写了后一个判定,这个判定就是为了防止()())这种情况,因为count此时为0
39                 System.out.println("完全匹配,最大嵌套数为"+num);
40             }
41             else{
42                 System.out.println("括号不匹配");
43             }
44         }
45         sc.close();
46     }
47     
48 }

 

posted @ 2017-09-22 21:39  zdtiio  阅读(170)  评论(0编辑  收藏  举报