20. Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: trueExample 2:
Input: "()[]{}"
Output: trueExample 3:
Input: "(]"
Output: falseExample 4:
Input: "([)]"
Output: falseExample 5:
Input: "{[]}"
Output: true解法
字节跳动提前批视频面试一面的笔试题,没有答好,总结一下:
思路很简单,使用一个栈来记录,如果是左括号就入栈,匹配的右括号就出栈。但是考虑清楚每种情况并不容易,条件的判断很重要。
这里用一个简单的稍兵就能使问题简化很多:
只遍历一次,时间复杂度 ; 使用了一个栈,最坏情况下((((((((((((()需要额外空间 。
Last updated
Was this helpful?