括号问题


下面的代码用于判断一个串中的括号是否匹配所谓匹配是指不同类型的括号必须左右呼应,可以相互包含,但不能交叉

例如:

..(..[..]..)..  是允许的

..(...[...)....].... 是禁止的

 1 import java.util.Stack;
 2 
 3 public class BracketQuestion {
 4     public static boolean isGoodBracket(String s) {
 5         Stack<Character> a = new Stack<Character>(); // 对象堆栈。
 6         for (int i = 0; i < s.length(); i++) {
 7             char c = s.charAt(i);
 8             if (c == '(')
 9                 a.push(')'); // 把项压入堆栈顶部。
10             if (c == '[')
11                 a.push(']');
12             if (c == '{')
13                 a.push('}');
14             if (c == ')' || c == ']' || c == '}') {
15                 if (a.size() == 0)
16                     return false;
17                 if (a.pop() != c) // 移除堆栈顶部的对象,并作为此函数的值返回该对象。
18                     return false;
19             }
20         }
21         if (a.size() != 0) // size() 返回此向量中的组件数。
22             return false;
23         return true;
24     }
25 
26     public static void main(String[] args) {
27         System.out.println(isGoodBracket("...(..[..)..]..{..(..)..}..."));
28         System.out.println(isGoodBracket("..(..{..[....]...}..)"));
29     }
30 }
原文地址:https://www.cnblogs.com/zhangping1993/p/5677120.html