字符串中括号配对检查(网易笔试题)

博客源地址

title: 字符串中括号配对检查


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:

{([])}
Yes

猜你喜欢

转载自blog.csdn.net/lewyu521/article/details/79967467