-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay36.java
More file actions
56 lines (46 loc) · 1.55 KB
/
Copy pathDay36.java
File metadata and controls
56 lines (46 loc) · 1.55 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
/*Parenthesis Checker
Given a string s, composed of different combinations of '(' , ')', '{', '}', '[', ']'. Determine whether the Expression is balanced or not.
An expression is balanced if:
Each opening bracket has a corresponding closing bracket of the same type.
Opening brackets must be closed in the correct order.
Examples :
Input: s = "[{()}]"
Output: true
Explanation: All the brackets are well-formed.
Input: s = "[()()]{}"
Output: true
Explanation: All the brackets are well-formed.
Input: s = "([]"
Output: false
Explanation: The expression is not balanced as there is a missing ')' at the end.
Input: s = "([{]})"
Output: false
Explanation: The expression is not balanced as there is a closing ']' before the closing '}'. */
/*import java.util.Stack;
class Solution {
static boolean isBalanced(String s) {
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) {
// If opening bracket, push to stack
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
}
// If closing bracket
else {
if (stack.isEmpty())
return false;
char top = stack.pop();
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
}
*/
/*⏱️ Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n) (stack) */