【网易笔试题】成对的括号

【网易笔试题】成对的括号_第1张图片
【网易笔试题】成对的括号_第2张图片

解题思路

将其他字符去掉之后,只剩下括号,遇见左括号入栈,右括号则弹栈,弹栈时无法匹配则返回false。


import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        String pattern = "[^\\[\\]\\{\\}\\(\\)]";
        String strNew = str.replaceAll(pattern, "");
        System.out.println(isValid(strNew));
    }

    public static boolean isValid(String str) {
        LinkedList stack = new LinkedList();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '(' || str.charAt(i) == '[' || str.charAt(i) == '{') {
                stack.push(str.charAt(i));
            } else if (str.charAt(i) == ')' && stack.size() > 0 && stack.peek() == '(') {
                stack.pop();
            } else if (str.charAt(i) == ']' && stack.size() > 0 && stack.peek() == '[') {
                stack.pop();
            } else if (str.charAt(i) == '}' && stack.size() > 0 && stack.peek() == '{') {
                stack.pop();
            } else {
                return false;
            }
        }
        return stack.isEmpty();
    }
}

你可能感兴趣的:(网易笔试题)