【Leetcode】Valid Parentheses

来源:互联网 发布:mac safari 收藏夹 编辑:程序博客网 时间:2024/06/06 05:40

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

这道题是栈的典型引用,只要遇到左括号就进栈,遇到右括号就出栈然后和左括号进行匹配,如果能匹配上就继续,不然就返回false,最后全部判断完后,只要栈空了就返回true

代码如下

public boolean isValid(String s) {if (s == null || s.length() == 0)return true;LinkedList<Character> stack = new LinkedList<Character>();for (int i = 0; i < s.length(); i++) {if (s.charAt(i) == '(')stack.push(s.charAt(i));if (s.charAt(i) == '[')stack.push(s.charAt(i));if (s.charAt(i) == '{')stack.push(s.charAt(i));if (s.charAt(i) == ')') {if (stack.isEmpty() || stack.pop() != '(')return false;}if (s.charAt(i) == ']') {if (stack.isEmpty() || stack.pop() != '[')return false;}if (s.charAt(i) == '}') {if (stack.isEmpty() || stack.pop() != '{')return false;}}if (stack.isEmpty())return true;return false;}



0 0
原创粉丝点击