算法4th 1.3.4 使用栈判定其中的括号是否配对完整
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); } } }
解题思路:
如果输入的是左括号就压栈
如果输入的是右括号就获取栈顶元素并判断是否和右括号配对
如果出栈元素与输入元素不配对 则配对错误
如果配对成功,此时所有元素都应该出栈,栈为空
学习的博客多用于在笔记中,防止笔记过于臃肿,所以将样例及运行结果放在博客中,后以超链接的形式记录在笔记中,所以有些博文过于单薄。如果有小伙伴遇到问题欢迎评论,看到就会回复,学渣一枚,加油努力。