Skip to content
This repository was archived by the owner on Jan 14, 2025. It is now read-only.

Commit 643b444

Browse files
committed
Add valid parentheses
1 parent 0d5162b commit 643b444

File tree

2 files changed

+80
-1
lines changed

2 files changed

+80
-1
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
2+
## Description
3+
4+
Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return `true` if the string is valid, and `false` if it's invalid.
5+
6+
### Examples
7+
```js
8+
"()" => true
9+
")(()))" => false
10+
"(" => false
11+
"(())((()())())" => true
12+
```
13+
14+
**Kata's link**: [Valid Parentheses](https://www.codewars.com/kata/valid-parentheses)
15+
16+
## Best Practices
17+
18+
**First:**
19+
```js
20+
// I had something that was smaller and looked cooler, but
21+
// this is how you'd want to write an actual parser.
22+
function validParentheses(string){
23+
var tokenizer = /[()]/g, // ignores characters in between; parentheses are
24+
count = 0, // pretty useless if they're not grouping *something*
25+
token;
26+
while(token = tokenizer.exec(string), token !== null){
27+
if(token == "(") {
28+
count++;
29+
} else if(token == ")") {
30+
count--;
31+
if(count < 0) {
32+
return false;
33+
}
34+
}
35+
}
36+
return count == 0;
37+
}
38+
```
39+
40+
**Second:**
41+
```js
42+
function validParentheses(parens){
43+
var indent = 0;
44+
45+
for (var i = 0 ; i < parens.length && indent >= 0; i++) {
46+
indent += (parens[i] == '(') ? 1 : -1;
47+
}
48+
49+
return (indent == 0);
50+
}
51+
```
52+
53+
**Third:**
54+
```js
55+
function validParentheses(parens){
56+
var n = 0;
57+
for (var i = 0; i < parens.length; i++) {
58+
if (parens[i] == '(') n++;
59+
if (parens[i] == ')') n--;
60+
if (n < 0) return false;
61+
}
62+
63+
return n == 0;
64+
}
65+
```
66+
67+
## My solutions
68+
```js
69+
function validParentheses(parens){
70+
//TODO
71+
const reg = /\(\)/g;
72+
while(reg.test(parens)) {
73+
parens = parens.replace(reg, '');
74+
}
75+
76+
return parens === '';
77+
}
78+
```

readme.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Here is my codewars homepage: https://www.codewars.com/users/dwqs.
1515
* [Sometimes](codewars/201512/sometimes.md)
1616
* [Adding ordinal indicator suffixes to numbers](codewars/201512/adding-ordinal-indicator-suffixes-to-numbers.md)
1717
* [Count IP Addresses](codewars/201512/count-ip-address.md)
18-
* [Regex Password Validation](codewars/201702/regex-password-validation.md)
18+
* [Regex Password Validation](codewars/git/regex-password-validation.md)
1919
* [Find Unique Number](codewars/201701/find-unique-number.md)
20+
* [Valid Parentheses](codewars/201807/valid-parentheses.md)
2021

0 commit comments

Comments
 (0)