LeetCode 20 Valid Parentheses

来源:互联网 发布:生鲜配送app源码 编辑:程序博客网 时间:2024/04/28 03:55

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.

public static boolean isValid(String s) {String[] strings = s.split("");Stack<String> stack = new Stack<String>();HashMap<String, String> map = new HashMap<String, String>();map.put("]", "[");map.put(")", "(");map.put("}", "{");for (String tmp : strings) {if (tmp.equals("{") || tmp.equals("(") || tmp.equals("[")) {stack.push(tmp);continue;}if (map.containsKey(tmp)) {if (stack.isEmpty() || !map.get(tmp).equals(stack.peek()))return false;stack.pop();}}if (stack.isEmpty()) return true;return false;}



0 0
原创粉丝点击