-
Notifications
You must be signed in to change notification settings - Fork 1
/
_0020_Valid_Parentheses.java
51 lines (43 loc) · 1.11 KB
/
_0020_Valid_Parentheses.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
// https://leetcode.com/problems/valid-parentheses/
import java.util.*;
public class _0020_Valid_Parentheses{
public static void main(String[] args) {
String str = "([)]";
Solution obj = new Solution();
System.out.println(obj.isValid(str));
}
}
class Solution {
HashMap<Character, Character>temp;
Stack<Character> stack = new Stack<>();
public boolean isValid(String s)
{
temp = new HashMap<>();
temp.put('(',')');
temp.put('{','}');
temp.put('[',']');
for(int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if(temp.containsKey(ch))
{
stack.add(temp.get(ch));
}
else if(ch == ')' || ch=='}' || ch==']')
{
if((stack.size() == 0) || ch != stack.pop())
{
return false;
}
}
}
if(stack.size() == 0)
{
return true;
}
else
{
return false;
}
}
}