题目描述
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: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
我的解法
解题思路
用一个string来做堆来储存左边的括号,如果遇到右边的括号就判断堆顶的左边括号和右边括号匹不匹配。
实现代码
1 | class Solution { |
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Valid Parentheses.
Memory Usage: 8.3 MB, less than 97.67% of C++ online submissions for Valid
虽然可以完成任务可以代码长了点
高票解法
实现代码
1 | class Solution { |
代码分析
用switch case和stack就能整洁很多