forked from lilong-dream/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses.java
More file actions
46 lines (37 loc) · 964 Bytes
/
Copy pathValidParentheses.java
File metadata and controls
46 lines (37 loc) · 964 Bytes
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
// Problem: http://oj.leetcode.com/problems/valid-parentheses/
// Analysis: http://blog.csdn.net/lilong_dream/article/details/21694751
// 1988lilong@163.com
import java.util.Stack;
public class ValidParentheses {
public boolean isValid(String s) {
if (s.length() == 0) {
return true;
}
Stack<Character> st = new Stack<Character>();
st.push(s.charAt(0));
for (int i = 1; i < s.length(); ++i) {
if (!st.empty() && isMatch(st.peek(), s.charAt(i))) {
st.pop();
}
else {
st.push(s.charAt(i));
}
}
if(st.empty()) {
return true;
}
return false;
}
public boolean isMatch(char s, char p) {
if ((s == '(' && p == ')') || (s == '{' && p == '}')
|| (s == '[' && p == ']')) {
return true;
}
return false;
}
public static void main(String[] args) {
ValidParentheses slt = new ValidParentheses();
String s = "(]";
System.out.println(slt.isValid(s));
}
}