Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2699
你的背包
你的背包 2020-11-27 11:39

For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

and so on but if the parenthesis/brackets is not mat

30条回答
  •  [愿得一人]
    2020-11-27 11:59

    import java.util.*;
    
    class StackDemo {
    
        public static void main(String[] argh) {
            boolean flag = true;
            String str = "(()){}()";
            int l = str.length();
            flag = true;
            Stack st = new Stack();
            for (int i = 0; i < l; i++) {
                String test = str.substring(i, i + 1);
                if (test.equals("(")) {
                    st.push(test);
                } else if (test.equals("{")) {
                    st.push(test);
                } else if (test.equals("[")) {
                    st.push(test);
                } else if (test.equals(")")) {
                    if (st.empty()) {
                        flag = false;
                        break;
                    }
                    if (st.peek().equals("(")) {
                        st.pop();
                    } else {
                        flag = false;
                        break;
                    }
                } else if (test.equals("}")) {
                    if (st.empty()) {
                        flag = false;
                        break;
                    }
                    if (st.peek().equals("{")) {
                        st.pop();
                    } else {
                        flag = false;
                        break;
                    }
                } else if (test.equals("]")) {
                    if (st.empty()) {
                        flag = false;
                        break;
                    }
                    if (st.peek().equals("[")) {
                        st.pop();
                    } else {
                        flag = false;
                        break;
                    }
                }
            }
            if (flag && st.empty())
                System.out.println("true");
            else
                System.out.println("false");
        }
    }
    

提交回复
热议问题