友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
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: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
思路分析
-
一刷
-
二刷
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
/**
* Runtime: 2 ms, faster than 60.99% of Java online submissions for Valid Parentheses.
*
* Memory Usage: 34.2 MB, less than 100.00% of Java online submissions for Valid Parentheses.
*
* @author D瓜哥 · https://www.diguage.com
* @since 2019-07-26 08:12
*/
public boolean isValid(String s) {
if (Objects.isNull(s) || s.length() == 0) {
return true;
}
Map<Character, Character> parenthesesMap = new HashMap<>(3);
parenthesesMap.put('(', ')');
parenthesesMap.put('{', '}');
parenthesesMap.put('[', ']');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char aChar = s.charAt(i);
if (parenthesesMap.containsKey(aChar)) {
stack.push(aChar);
} else {
if (stack.isEmpty()) {
return false;
}
char peek = stack.pop();
if (aChar != parenthesesMap.get(peek)) {
return false;
}
}
}
return stack.isEmpty();
}
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
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2024-09-13 16:51:17
*/
public boolean isValid(String s) {
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '[' || c == '{') {
stack.addLast(c);
} else if (c == ')') {
if (stack.isEmpty() || stack.peekLast() != '(') {
return false;
} else {
stack.removeLast();
}
} else if (c == ']') {
if (stack.isEmpty() || stack.peekLast() != '[') {
return false;
} else {
stack.removeLast();
}
} else if (c == '}') {
if (stack.isEmpty() || stack.peekLast() != '{') {
return false;
} else {
stack.removeLast();
}
}
}
return stack.isEmpty();
}