-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses.java
More file actions
45 lines (41 loc) · 1.2 KB
/
ValidParentheses.java
File metadata and controls
45 lines (41 loc) · 1.2 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
package com.leetcode;
import java.util.Stack;
/**
* Created by jamylu on 2018/1/2.
* leetcode020
* 括号匹配
*/
public class ValidParentheses {
public static void main(String args[]) {
String s = "()[]{[()]}";
System.out.println(isValid(s));
}
public static boolean isValid(String s) {
Stack<Character> st = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
st.push(s.charAt(i));
} else if (s.charAt(i) == ')') {
if (!st.isEmpty() && st.peek() == '(')
st.pop();
else
return false;
} else if (s.charAt(i) == ']') {
if (!st.isEmpty() && st.peek() == '[')
st.pop();
else
return false;
} else if (s.charAt(i) == '}') {
if (!st.isEmpty() && st.peek() == '{')
st.pop();
else
return false;
}
}
if (st.isEmpty()) {
return true;
} else {
return false;
}
}
}