Repository navigation
Expand file tree
/
Copy pathP20ValidParentheses.java
More file actions
94 lines (87 loc) · 2.3 KB
/
Copy pathP20ValidParentheses.java
File metadata and controls
94 lines (87 loc) · 2.3 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package leetcode.editor.cn;
//给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
//
// 有效字符串需满足:
//
//
// 左括号必须用相同类型的右括号闭合。
// 左括号必须以正确的顺序闭合。
//
//
// 注意空字符串可被认为是有效字符串。
//
// 示例 1:
//
// 输入: "()"
//输出: true
//
//
// 示例 2:
//
// 输入: "()[]{}"
//输出: true
//
//
// 示例 3:
//
// 输入: "(]"
//输出: false
//
//
// 示例 4:
//
// 输入: "([)]"
//输出: false
//
//
// 示例 5:
//
// 输入: "{[]}"
//输出: true
// Related Topics 栈 字符串
// 👍 2048 👎 0
import java.util.Stack;
public class P20ValidParentheses {
public static void main(String[] args) {
Solution solution = new P20ValidParentheses().new Solution();
System.out.println(solution.isValid("{[]}"));
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean isValidB(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(')');
} else if (c == '{') {
stack.push('}');
} else if (c == '[') {
stack.push(']');
} else if (stack.isEmpty() || c != stack.pop()) {
return false;
}
}
return stack.isEmpty();
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (!stack.empty()) {
char pop = stack.pop();
if ((chars[i] == '}' && pop == '{') || (chars[i] == ']' && pop == '[')
|| (chars[i] == ')' && pop == '(')) {
} else {
stack.push(pop);
stack.push(chars[i]);
}
} else {
stack.push(chars[i]);
}
}
return stack.isEmpty();
}
}
//leetcode submit region end(Prohibit modification and deletion)
}