Skip to content

Commit 4f7d780

Browse files
committed
Add README for Valid Parentheses Problem
1 parent 19d9ba7 commit 4f7d780

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

L-B/0022 ValidParentheses/README.md

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Valid Parentheses (L-B)
2+
3+
## Problem
4+
5+
Given a string `s` containing just the characters `'(', ')', '{', '}', '['` and `']'`, determine if the input string is valid.
6+
7+
An input string is valid if:
8+
9+
- Open brackets must be closed by the same type of brackets.
10+
- Open brackets must be closed in the correct order.
11+
- Every close bracket has a corresponding open bracket of the same type.
12+
13+
## Testcases
14+
15+
- Input: `"()"` <br>
16+
Output: `true`
17+
18+
- Input: `"()[]{}"` <br>
19+
Output: `true`
20+
21+
- Input: `"(]"` <br>
22+
Output: `false`
23+
24+
## Solution
25+
26+
```javascript
27+
const ValidParentheses = (s) => {
28+
var stack = [];
29+
30+
obj = {
31+
"(": ")",
32+
"{": "}",
33+
"[": "]",
34+
};
35+
36+
for (let i of s) {
37+
if (Object.keys(obj).includes(i)) {
38+
stack.push(i);
39+
} else if (stack && obj[stack[stack.length - 1]] == i) {
40+
stack.pop();
41+
} else {
42+
return false;
43+
}
44+
}
45+
46+
return stack.length === 0 ? true : false;
47+
};
48+
```
49+
50+
## How it works
51+
52+
- We initialize a `stack` to keep track of the parentheses.
53+
- We make an object `obj` which keeps the values for the corresponding opening and closing brackets.
54+
- The function runs a for loop for the string `s`.
55+
- If the current letter is part of the `obj`'s keys, then push the letter to the `stack`.
56+
- Else if the stack is not empty and the top of the `stack` corresponds with the current letter, then pop an element out of the `stack`.
57+
- Else, return `false`
58+
- If the for loop terminates normally then return `true` if the stack is empty or else `false`.
59+
60+
## References
61+
62+
- [LeetCode](https://leetcode.com/problems/valid-parentheses/)
63+
64+
## Problem Added By
65+
66+
- [GitHub](https://www.github.com/khairalanam)
67+
- [LinkedIn](https://www.linkedin.com/in/khair-alanam-b27b69221/)
68+
- [Twitter](https://twitter.com/khair_alanam)
69+
70+
## Contributing
71+
72+
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

0 commit comments

Comments
 (0)