算法4th 1.3.4 使用栈判定其中的括号是否配对完整

时间:2020-06-30 20:58:47   收藏:0   阅读:52
public class Parentheses {
    public static void main(String[] args) {
        Stack<String> s = new Stack<>();
        String string = StdIn.readString();
        String[] inputs = string.split(""); //获取每一个字符
        for (String input : inputs){
            if (input.equals("{")||input.equals("(")||input.equals("[")){
                s.push(input);
            }else if (!s.isEmpty()){
                if (input.equals("}")){
                    if (!s.pop().equals("{")){
                        System.out.println(false);
                        break;
                    }
                }
                if (input.equals(")")){
                    if (!s.pop().equals("(")){
                        System.out.println(false);
                        break;
                    }
                }
                if (input.equals("]")){
                    if (!s.pop().equals("[")){
                        System.out.println(false);
                        break;
                    }
                }
            }
        }
        if (s.isEmpty()){
            System.out.println(true);
        }
    }
}
解题思路:
如果输入的是左括号就压栈
如果输入的是右括号就获取栈顶元素并判断是否和右括号配对
如果出栈元素与输入元素不配对 则配对错误
如果配对成功,此时所有元素都应该出栈,栈为空
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!