forked from lilong-dream/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path032ValidParentheses.java
More file actions
52 lines (42 loc) · 1.23 KB
/
032ValidParentheses.java
File metadata and controls
52 lines (42 loc) · 1.23 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
// Author: Li Long, [email protected]
// Date: Apr 17, 2014
// Source: http://oj.leetcode.com/problems/valid-parentheses/
// Analysis: http://blog.csdn.net/lilong_dream/article/details/21694751
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
// determine if the input string is valid.
// The brackets must close in the correct order,
// "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
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));
}
}