标签:== alt 匹配 false 还需 match log print rgs
1 public class Match {
2 public boolean match(String expression) {
3 char[] array = expression.toCharArray();
4 char[] stack = new char[array.length];
5 int top = 0;
6 for (int i = 0; i < array.length; i++) {
7 if (array[i] == ‘(‘ || array[i] == ‘[‘ || array[i] == ‘{‘) {
8 stack[top++] = array[i];
9 }
10 }
11
12 /* 和top进行匹配 */
13 for (int i = 0; i < array.length; i++) {
14 if (array[i] == ‘)‘ || array[i] == ‘]‘ || array[i] == ‘}‘) {
15 if (stack[top] != ‘(‘ || stack[top] != ‘[‘ || stack[top] != ‘{‘) {
16 if (top > 0) {
17 top--;
18 } else {
19 /* 如果top减到0还需要减,则说明还有括号没有匹配 */
20 return false;
21 }
22 }
23 }
24 }
25 /* 若top不为0,说明还有括号没有匹配,否则匹配成功 */
26 if (top != 0) {
27 return false;
28 } else {
29 return true;
30 }
31 }
32
33 public static void main(String[] args) {
34 String expression = "{}}][{)";
35 Match match = new Match();
36 System.out.println("括号是否匹配:" + match.match(expression));
37 }
38 }
输出结果为:
标签:== alt 匹配 false 还需 match log print rgs
原文地址:http://www.cnblogs.com/mjyung/p/6731099.html