Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 5f80dec

Browse files
Create Valid_Parentheses.js
1 parent 17b5bd5 commit 5f80dec

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

LeetcodeProblems/Valid_Parentheses.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
Valid Parentheses
3+
4+
https://leetcode.com/problems/valid-parentheses/description/
5+
6+
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
7+
8+
An input string is valid if:
9+
10+
Open brackets must be closed by the same type of brackets.
11+
Open brackets must be closed in the correct order.
12+
Note that an empty string is also considered valid.
13+
14+
Example 1:
15+
16+
Input: "()"
17+
Output: true
18+
Example 2:
19+
20+
Input: "()[]{}"
21+
Output: true
22+
Example 3:
23+
24+
Input: "(]"
25+
Output: false
26+
Example 4:
27+
28+
Input: "([)]"
29+
Output: false
30+
Example 5:
31+
32+
Input: "{[]}"
33+
Output: true
34+
*/
35+
36+
var isValid = function(s) {
37+
if(s.length === 0)
38+
return true;
39+
var queue = [];
40+
for(var i = 0; i < s.length; i++) {
41+
const elem = s[i];
42+
if(elem === "(" || elem === "[" || elem === "{") {
43+
queue.unshift(elem);
44+
} else {
45+
if(queue.length === 0)
46+
return false;
47+
48+
const elemQueue = queue.shift();
49+
if(elemQueue === "(" && elem !== ")" ||
50+
elemQueue === "[" && elem !== "]" ||
51+
elemQueue === "{" && elem !== "}")
52+
return false;
53+
}
54+
}
55+
56+
return queue.length === 0;
57+
};
58+
59+
var main = function(){
60+
console.log(isValid(""));
61+
console.log(isValid("()"));
62+
console.log(isValid("([)]"));
63+
console.log(isValid("{[()]}{[()]}"));
64+
console.log(isValid("{[())()]}"));
65+
}
66+
67+
module.exports.main = main

0 commit comments

Comments
 (0)