leetcode解题之20 # Valid Parentheses Java版

来源:互联网 发布:万方数据库 知网 编辑:程序博客网 时间:2024/06/17 09:36

20. Valid Parentheses

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 boolean isValid(String s) {Map<Character, Character> map = new HashMap<>();map.put('(', ')');map.put('[', ']');map.put('{', '}');Stack<Character> stack = new Stack<Character>();if (s.length() % 2 != 0 || s == null || s.length() == 0)return false;for (int i = 0; i < s.length(); i++) {if ((s.charAt(i) == '[') || s.charAt(i) == '{' || s.charAt(i) == '(')stack.push(s.charAt(i));//注意先判断size()else if (stack.size()>0&&(map.get(stack.peek()) ==s.charAt(i) ))stack.pop();elsereturn false;}return stack.empty();}


0 0