Description
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:
1 | Input: "()" |
Example 2:
1 | Input: "()[]{}" |
Example 3:
1 | Input: "(]" |
Example 4:
1 | Input: "([)]" |
Example 5:
1 | Input: "{[]}" |
Difficulty: Easy
Code:
1 | class Solution { |
题意
给定一个字符串,只包含”(){}[]”,判断输入到字符串是否有效。开括号和必须以同样到类型到闭括号关闭,开括号必须以正确到顺序关闭。
Solution 1
看到开括号必要要以相同到顺序关闭,自然想到栈,读取到开括号则压栈,读取到闭括号则出栈并判断是否配对。读取完栈需为空,否则无效。
1 | class Solution { |
时间复杂度: O(N),字符串长度。
空间复杂度: O(N),字符串长度。
Solution 2
把所有括号符号依次拼接成字符串,Stack里面存括号在字符串中位置,以简化计算。
1 | public class Solution { |
时间复杂度: O(N),字符串长度。
空间复杂度: O(N),字符串长度。