Skip to content

Commit 72763cf

Browse files
committed
Add solution #20
1 parent d838433 commit 72763cf

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
13|[Roman to Integer](./0013-roman-to-integer.js)|Easy|
2222
14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy|
2323
17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium|
24+
20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy|
2425
21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy|
2526
27|[Remove Element](./0027-remove-element.js)|Easy|
2627
31|[Next Permutation](./0031-next-permutation.js)|Medium|

solutions/0020-valid-parentheses.js

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 20. Valid Parentheses
3+
* https://leetcode.com/problems/valid-parentheses/
4+
* Difficulty: Easy
5+
*
6+
* Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
7+
* determine if the input string is valid.
8+
*
9+
* An input string is valid if:
10+
* - Open brackets must be closed by the same type of brackets.
11+
* - Open brackets must be closed in the correct order.
12+
*/
13+
14+
/**
15+
* @param {string} s
16+
* @return {boolean}
17+
*/
18+
var isValid = function(s) {
19+
const map = {
20+
'(': ')',
21+
'[': ']',
22+
'{': '}'
23+
}
24+
const stack = [];
25+
26+
for (let i = 0; i < s.length; i++) {
27+
if (map[s[i]]) {
28+
stack.push(map[s[i]]);
29+
} else {
30+
if (stack.pop() !== s[i]) {
31+
return false;
32+
}
33+
}
34+
}
35+
36+
return stack.length === 0;
37+
};

0 commit comments

Comments
 (0)