forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20_Valid_Parentheses
75 lines (62 loc) · 2.29 KB
/
20_Valid_Parentheses
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
// https://leetcode.com/problems/valid-parentheses/
// My approach
class Solution {
private HashMap<Character,Character> mappings;
public Solution(){
this.mappings = new HashMap<Character,Character>();
this.mappings.put('(',')');
this.mappings.put('[',']');
this.mappings.put('{','}');
}
public boolean isValid(String s){
Stack<Character> stack = new Stack<Character>();
char ch[] = s.toCharArray();
for(int i=0;i<s.length();i++){
if(ch[i]=='(' || ch[i]=='[' || ch[i]=='{')stack.push(ch[i]);
else if(stack.isEmpty()==false)
{if(stack.peek()=='(' && ch[i]==mappings.get('('))stack.pop();
else if(stack.peek()=='[' && ch[i]==mappings.get('['))stack.pop();
else if(stack.peek()=='{' && ch[i]==mappings.get('{'))stack.pop();
else return false;}
else
return false;
}
if(stack.isEmpty())
return true;
else
return false;
}
}
// Solution
class Solution {
// Hash table that takes care of the mappings.
private HashMap<Character, Character> mappings;
// Initialize hash map with mappings. This simply makes the code easier to read.
public Solution() {
this.mappings = new HashMap<Character, Character>();
this.mappings.put(')', '(');
this.mappings.put('}', '{');
this.mappings.put(']', '[');
}
public boolean isValid(String s) {
// Initialize a stack to be used in the algorithm.
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// If the current character is a closing bracket.
if (this.mappings.containsKey(c)) {
// Get the top element of the stack. If the stack is empty, set a dummy value of '#'
char topElement = stack.empty() ? '#' : stack.pop();
// If the mapping for this bracket doesn't match the stack's top element, return false.
if (topElement != this.mappings.get(c)) {
return false;
}
} else {
// If it was an opening bracket, push to the stack.
stack.push(c);
}
}
// If the stack still contains elements, then it is an invalid expression.
return stack.isEmpty();
}
}