判断字符串括号是否闭合(){}[]

今天去面试做了一道狠可爱的题目,判断一个字符串的括号自否闭合(包括大小中括号)

当时没马上做出来,只是说了大概的思路

一开始的思路就是判断每种括号的开闭数量是否相等,其实虽然也能实现但是搞得太复杂了;

回来后查了下发现很多都是利用堆栈实现的,

下面是不用栈实现的方式:

只需设一个常量,

开+1,

闭-1,

闭合的话为0,

没闭合的话不为0,

出现<0即为顺序不对

 1     public static void main(String[] args){
 2         String str = "{123}[23](11{231)}";
 3         countBrackets(str);
 4     }
 5     /**
 6      * 判断括号是否关闭
 7      * 遍历字符串
 8      * 左括号时+1,右括号时-1
 9      * 当出现小于0的情况时,括号顺序不对
10      * 最后不等于0的话说明没关闭
11      * @param str
12      */
13     public static void  countBrackets(String str){
14         int da=0,zh=0,xi=0;
15         for(int i=0;i<str.length();i++){
16             char s = str.charAt(i);
17             if(s=='{'){
18                 da+=1;
19             }
20             if(s=='['){
21                 zh+=1;
22             }
23             if(s=='('){
24                 xi+=1;
25             }
26             if(s=='}'){
27                 da-=1;
28             }
29             if(s==']'){
30                 zh-=1;
31             }
32             if(s==')'){
33                 xi-=1;
34             }
35             if(da<0||zh<0||xi<0){
36                 break;
37             }
38         }
39         if(da!=0||zh!=0||xi!=0){
40             System.out.println("error");
41         }else{
42             System.out.println("ok");
43         }
44     }

 

posted @ 2017-05-10 23:51  空知大猩猩  阅读(3187)  评论(1编辑  收藏  举报