Skip to content

Commit 1fab36c

Browse files
committed
Added 'Valid Parentheses'
1 parent 20fe4a4 commit 1fab36c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Diff for: Valid Parentheses.java

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// https://leetcode.com/problems/valid-parentheses/
2+
// https://www.youtube.com/watch?v=WTzjTskDFMg&t=316
3+
4+
class Solution {
5+
public boolean isValid(String s) {
6+
7+
/*
8+
* Time Complexity: O(n) where n = length of input string. String will be iterated
9+
* and worse case is that it's long and has a valid parentheses.
10+
*
11+
* Space Complexity: O(n) where n = length of stack. Stack height is based of string's
12+
* length. Also, although hash map was created, it size isn't dynamic, which is why
13+
* it didn't influence the space complexity.
14+
*/
15+
16+
// Create a hash map
17+
Map<Character, Character> closingCharacters = new HashMap<>(Map.of(
18+
'}', '{',
19+
']', '[',
20+
')', '('
21+
));
22+
23+
// Create a stack
24+
Stack<Character> mainStack = new Stack<>();
25+
26+
// Iterate string
27+
for (int i = 0; i < s.length(); i++) {
28+
29+
Character c = Character.valueOf(s.charAt(i));
30+
31+
// Check if c is a closing character
32+
if (closingCharacters.containsKey(c)) {
33+
34+
// If stack isn't empty AND stack head is a matching pair with c, pop stack head.
35+
// If not, return false because the string doesn't have a valid parentheses
36+
if (!mainStack.empty() && mainStack.peek() == closingCharacters.get(c)) {
37+
mainStack.pop();
38+
}
39+
else {
40+
return false;
41+
}
42+
}
43+
else { // If c is another opening character, add it to stack
44+
mainStack.push(c);
45+
}
46+
}
47+
48+
// If stack is empty, then string had valid parentheses. If not, return false
49+
return mainStack.empty();
50+
}
51+
}

0 commit comments

Comments
 (0)