forked from qiurunze123/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lc20.java
54 lines (51 loc) · 1.46 KB
/
lc20.java
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
package code;
import java.util.HashMap;
import java.util.Stack;
/*
* 20. Valid Parentheses
* 题意:括号匹配
* 难度:Easy
* 分类:String, Stack
*/
public class lc20 {
public static void main(String[] args) {
System.out.println(isValid("]"));
}
public static boolean isValid(String s) {
Stack<String> st = new Stack();
HashMap<String,String> hm = new HashMap();
hm.put("(",")");
hm.put("[","]");
hm.put("{","}");
for (int i = 0; i < s.length() ; i++) {
char ch = s.charAt(i);
if(ch=='(' || ch=='[' || ch=='{'){
st.push(String.valueOf(ch));
}else{
if(st.size()==0)
return false;
String temp1 = hm.get(st.pop());
String temp2 = String.valueOf(ch);
if(!temp1.equals(temp2))
return false;
}
}
if(st.size()==0)
return true;
return false;
}
public boolean isValid2(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
}