-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidParenthesis.java
94 lines (82 loc) · 2.65 KB
/
ValidParenthesis.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
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
92
93
94
package string;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class ValidParenthesis {
/**
* Main method of the class for the following question:
* Check if the parenthesis string is valid or not. <br />
* <strong>Example 1:</strong> <br />
* Input: ()[]{} <br />
* Output: true <br />
*
* <strong>Example 2:</strong> <br />
* Input: ([{}]) <br />
* Output: true <br />
*
* <strong>Example 3:</strong> <br />
* Input: ( <br />
* Output: false <br />
*
* */
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.print("Enter Parenthesis string: ");
String str = scanner.nextLine();
System.out.println(isValidParenthesis(str));
System.out.println(isValidParenthesisWithHashMap(str));
scanner.close();
}
/**
* Method to check if the parenthesis string is valid or not. (brute force)
* */
public static boolean isValidParenthesis(String str) {
if (str == null || str.isEmpty()) {
return true;
}
if (str.length() % 2 != 0) {
return false;
}
Stack<Character> stack = new Stack<>();
for (char c : str.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else if (c == ')' && !stack.isEmpty() && stack.peek() == '(') {
stack.pop();
} else if (c == '}' && !stack.isEmpty() && stack.peek() == '{') {
stack.pop();
} else if (c == ']' && !stack.isEmpty() && stack.peek() == '[') {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
/**
* Method to check if the parenthesis string is valid or not. (using HashMap)
* */
public static boolean isValidParenthesisWithHashMap(String str) {
if (str == null || str.isEmpty()) {
return true;
}
if (str.length() % 2 != 0) {
return false;
}
Stack<Character> stack = new Stack<>();
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put('}', '{');
map.put(']', '[');
for (char c : str.toCharArray()) {
if (map.containsKey(c)) {
if (stack.isEmpty() || map.get(c) != stack.pop()) {
return false;
}
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
}