-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathvalid-parentheses.js
94 lines (81 loc) · 1.88 KB
/
valid-parentheses.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
function validParentheses(parens){
// ( - 1
// ) - -1
// a place to store the sum
// initialized to 0
let sum = 0;
// iterate over the parens
for (let i = 0; i < parens.length; i++) {
const paren = parens[i];
// if a open paren
if (paren === '(') {
// add 1 to the sum
sum += 1;
} else {
// if a closing paren
// subtract 1 from the sum
sum -= 1;
}
// if the sum is negative, return false
if (sum < 0) {
return false;
}
}
// if the sum is equal to 0, return true
return sum === 0;
}
function validParentheses(parens){
const values = {
'(': 1,
')': -1
}
let sum = 0;
for (let i = 0; i < parens.length; i++) {
const paren = parens[i];
sum += values[paren];
if (sum < 0) {
return false;
}
}
return sum === 0;
}
function validParentheses(parens){
const values = {
'(': 1,
')': -1
}
let sum = 0;
const isPositiveSum = Array.prototype.every.call(parens, (paren) => {
sum += values[paren];
if (sum < 0) {
return false;
}
return true;
});
return isPositiveSum && sum === 0;
}
function validParentheses(parens, sum = 0){
return Array.prototype.every.call(parens, (paren) => {
sum += {
'(': 1,
')': -1
}[paren];
return sum >= 0;
}) && sum === 0;
}
function validParentheses(parens, sum = 0){
return Array.prototype.every.call(parens, (paren) => {
return (sum += {
'(': 1,
')': -1
}[paren]) >= 0;
}) && sum === 0;
}
function validParentheses(parens, sum = 0){
return [].every.call(parens, (paren) => (sum += { '(': 1, ')': -1 }[paren]) >= 0) && sum === 0;
}
function validParentheses(parens, sum = 0){
return [].every.call(parens, (paren) => (sum += paren === '(' ? 1 : -1) >= 0) && sum === 0;
}
console.log(validParentheses( "()" ), true);
console.log(validParentheses( "())" ), false);