423. 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.
Example
Example 1:
Input: "([)]"
Output: False
Example 2:
Input: "()[]{}"
Output: True
Challenge
Use O(n) time, n is the number of parentheses.
思路:
遍历String,左向括号入栈,当遇到右向括号时,(如果栈此时为空,则返回false)pop一个出来,并与右向括号匹配,看是否为一对。如果不是一对,则返回false。
遍历完整个数组,记得再检查栈是否为空,即左向括号数量=右向括号数量。所以 return (stack.isEmpty());
代码:
for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(' || s.charAt(i) == '['||s.charAt(i) == '{') stack.push(s.charAt(i)); else{ if (stack.isEmpty()) return false; char pop = stack.pop(); if (s.charAt(i) == ')' && (pop == '[' || pop == '{')) return false; if (s.charAt(i) == ']' && (pop == '(' || pop == '{')) return false; if (s.charAt(i) == '}' && (pop == '(' || pop == '[')) return false; } }return stack.isEmpty(); }