标签:cte not empty ++ new col min pre 经历
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.
数据结构:用stack。看到左括号推入对应的右括号。看到右括号检查1.stack是不是空的弹不出来了 2.stack弹出来的是不是自己。看到其他符号肯定错。最后都遍历一遍了确认stack是不是空了,空了就说明全匹配了可以点头,否则说明有些没配上还是不行。
实现:
class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c == ‘(‘) { stack.push(‘)‘); } else if (c == ‘{‘) { stack.push(‘}‘); } else if (c == ‘[‘) { stack.push(‘]‘); } else if (c == ‘)‘ || c == ‘}‘ || c == ‘]‘) { if (stack.isEmpty() || stack.pop() != c) { return false; } } else { return false; } } // 千万小心不是经历完上面的for就是可以返回true了,一定要全匹配,stack空了才行,如果还剩下左括号没配上就还是错。 return stack.isEmpty(); } }
leetcode20- Valid Parentheses- easy
标签:cte not empty ++ new col min pre 经历
原文地址:http://www.cnblogs.com/jasminemzy/p/7948228.html