今天去面試做了一道狠可愛的題目,判斷一個字符串的括號自否閉合(包括大小中括號)
當時沒馬上做出來,只是說了大概的思路
一開始的思路就是判斷每種括號的開閉數量是否相等,其實雖然也能實現但是搞得太復雜了;
回來后查了下發現很多都是利用堆棧實現的,
下面是不用棧實現的方式:
只需設一個常量,
開+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 }