LeetCode 20. 有效的括号
题目描述
思路分析
栈
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func isValid(s string) bool {
stack := make([]rune, 0)
hashtable := map[rune]rune{
'(': ')',
'[': ']',
'{': '}',
}
for _, c := range s {
if c == '(' || c == '[' || c == '{' {
stack = append(stack, c)
} else {
if len(stack) > 0 && hashtable[stack[len(stack)-1]] == c {
stack = stack[:len(stack)-1]
} else {
return false
}
}
}
return len(stack) == 0
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func isValid(s string) bool {
stack := make([]rune, 0)
hashtable := map[rune]rune{
')': '(',
']': '[',
'}': '{',
}
for _, c := range s {
if c == '(' || c == '[' || c == '{' {
stack = append(stack, c)
} else {
if len(stack) == 0 || stack[len(stack)-1] != hashtable[c] {
return false
} else {
stack = stack[:len(stack)-1]
}
}
}
return len(stack) == 0
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (map.containsKey(c)) {
if (stack.isEmpty() || stack.peek() != map.get(c)) {
return false;
} else {
stack.pop();
}
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
}
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用