-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses.java
More file actions
91 lines (79 loc) · 2.62 KB
/
ValidParentheses.java
File metadata and controls
91 lines (79 loc) · 2.62 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
*/
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
HashMap<Character,Character> map = new HashMap<Character,Character>();
map.put('(',')');
map.put('[',']');
map.put('{','}');
int left = 0;
if(s.length() == 0)
return true;
if(map.containsValue(s.charAt(0)))
return false;
for(int i=0 ; i<s.length() ; i++)
{
//System.out.println("current character " + s.charAt(i));
if( map.containsKey(s.charAt(i)))
{
stack.push(s.charAt(i));
left++;
//System.out.println("stack peek " + stack.peek());
//System.out.println("stack size " + stack.size());
//System.out.println("left " + left);
}
if(map.containsValue(s.charAt(i)))
{
if(stack.size() == 0 )
{
return false;
}
if(stack.size()> 0)
{
if(map.get(stack.peek()) == s.charAt(i))
{
//System.out.println("stack peek " + stack.peek());
stack.pop();
//System.out.println("stack size " + stack.size());
left--;
//System.out.println("left " + left);
continue;
}
else
{
int count = 0;
Stack<Character> temp = new Stack<>();
temp = stack;
for(int k=0 ; k<temp.size();k++)
{
if(map.containsValue(s.charAt(i)) && temp.pop() == s.charAt(i))
count++;
}
if(count == 0 )
return false;
}
}
}
}
if(left == 0 && stack.size()== 0)
return true;
else
return false;
}
}