字符串中括号配对检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.*;
//检验{【】}【】括号匹配
public class Main {
public static void main(String[] args) {
int flag = 1, l;
String s = "{([])}";
int num = s.length();
char[] arr = s.toCharArray();
System.out.println(arr);
// Stack<> stack;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < num; i++) {
if ('{' == arr[i] || '(' == arr[i] || '[' == arr[i]) {
stack.push(arr[i]);
} else {
if (stack.isEmpty()) {
flag = 1;
} else {
if (('}' == arr[i] && stack.pop() == '{') || ')' == arr[i] && stack.pop() == '('
|| ']' == arr[i] && stack.pop() == '[') {
stack.pop();
}
}
}
}
if (flag == 1 && stack.isEmpty())
System.out.println("Yes");
else {
System.out.println("NO");
}
}
}

Output:

1
2
{([])}
Yes

请我吃辣条吧!