-
Notifications
You must be signed in to change notification settings - Fork 0
/
0020_Valid_Parentheses.java
42 lines (35 loc) · 1.14 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
/*
* 20. Valid Parentheses
* Problem Link: https://leetcode.com/problems/valid-parentheses/
* Difficulty: Easy
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (c == '(' || c == '[' || c == '{'){
stack.push(c);
}
// if no matching bracket, then not valid
else if (stack.isEmpty()) {
return false;
// check for matching bracket
} else {
char lastElement = stack.pop();
if ((c == ']' && lastElement != '[') ||
(c == ')' && lastElement != '(') ||
(c == '}' && lastElement != '{')
){
return false;
}
}
}
return stack.isEmpty();
}
}