基於棧(Stack)實現括號匹配

public class BracketMatching {
    
       public static void main(String[] args) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        List<String> read = new ArrayList<>();
        while (true){
            String s = reader.readLine();
            if ("quit".equalsIgnoreCase(s)){
                break;
            }
            read.add(s);
        }
        //read.add("}}({}[]()((()))[{()}]{[([{[{{}}]}])]}");

        List<String> stringList = read.stream().flatMap(s -> Arrays.stream(s.split(""))).collect(Collectors.toList());
        Stack<String> stack = new Stack<>();
        for (int i =0;i < stringList.size();++i){
            if (stack.empty()){
                stack.push(stringList.get(i));
            }else {
                String pop = stack.pop();
                if ("{".equals(pop) && "}".equals(stringList.get(i))){

                }else if ("(".equals(pop) && ")".equals(stringList.get(i))){

                }else if ("[".equals(pop) && "]".equals(stringList.get(i))){

                }else {
                    stack.push(pop);
                    stack.push(stringList.get(i));
                }
            }
        }
        System.out.println(stack.empty());
    } 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章