avatar

day15_栈_20_ 有效的括号

题目

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

1
2
输入: "()"
输出: true

示例 2:

1
2
输入: "()[]{}"
输出: true

示例 3:

1
2
输入: "(]"
输出: false

示例 4:

1
2
输入: "([)]"
输出: false

示例 5:

1
2
输入: "{[]}"
输出: true

Related Topics

  • 字符串

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public boolean isValid(String s) {
Map<Character,Character> map = new HashMap<>();
map.put('}','{');
map.put(']','[');
map.put(')','(');
char[] chars = s.toCharArray();
Stack<Character> stack = new Stack<>();
for(int i = 0; i < chars.length; i++){
char c = s.charAt(i);

// If the current character is a closing bracket.
if (map.containsKey(c)) {

// Get the top element of the stack. If the stack is empty, set a dummy value of '#'
char topElement = stack.empty() ? '#' : stack.pop();

// If the mapping for this bracket doesn't match the stack's top element, return false.
if (topElement != map.get(c)) {
return false;
}
} else {
// If it was an opening bracket, push to the stack.
stack.push(c);
}

}
return stack.isEmpty();

}
}

//runtime:3 ms
//memory:37.7 MB
文章作者: 无知的小狼
文章链接: https://bytedance.press/2020/05/09/20200501/day15_%E6%A0%88_20_%20%E6%9C%89%E6%95%88%E7%9A%84%E6%8B%AC%E5%8F%B7/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 无知的小狼

评论