## DEV Community is a community of 757,079 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# code every day with me

--DAY 6--
Hi, I am going to make #100DaysOfCode Challenge.Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
Now let's solve problem today:
-Problem: Valid Parentheses
-Detail: https://leetcode.com/problems/valid-parentheses/
-My solution (javascript):

``````var isValid = function(s) {
if(s.length%2!=0) return false;
let map = new Map([
['[',']'],['(',')'],['{','}']
])
let stack=[],closeChar=[];
for(let x of s){
if('([{'.includes(x)) stack.push(x);
else if(x == map.get(stack[stack.length-1])){
stack.pop();
}
else closeChar.push(x);
}
return(stack.length==0&&closeChar.length==0)?true:false;
};
``````

-->If you have better solution or any question, please comment below. I will appreciate.

## Discussion (5) Frank Wisniewski
``````var isValid = function (s) {
c = true;
while(c){
if (s.search(/\(\)|\{\}|\[\]/g) >= 0 )
s=s.replace(/\(\)|\{\}|\[\]/g,'')
else
c = false
}
return (s.length==0) ? true : false
}
console.log (isValid('[()()[]{}]'))
console.log (isValid('[({)(})[]{}]'))
`````` Frank Wisniewski • Edited on

Yes regex.
You could shorten it to:

``````var isValid = function (s) {
while(s.search(/\(\)|\{\}|\[\]/g) >= 0)
s=s.replace(/\(\)|\{\}|\[\]/g,'')
return (s.length==0) ? true : false
}
console.log (isValid('[()()[]{}]'))
console.log (isValid('[({)(})[]{}]'))
`````` LUKESHIRU

A few tips:

• Avoid single letter names such as `s` or `x`, your teammates and your future self will be thankful.
• Try to always use `===` and `!==` instead of `==` and `!=` which are less reliable.
• You can use a plain object instead of a map:
``````const map = {
"[": "]",
"(": ")",
"{": "}"
};
``````
• When working with boolean expresions, you don't need a ternary, so you can change this:
``````return stack.length == 0 && closeChar.length == 0 ? true : false;
``````

With this:

``````return stack.length === 0 && closeChar.length === 0;
``````

Finally, here is my version using your same logic but without any `for`, `return` or anything like that:

``````const isValid = string =>
string.length % 2 === 0 &&
[...string]
.reduce(
([stack, closeChar], char) =>
"([{".includes(char)
? [[...stack, char], closeChar]
: char ===
{
"[": "]",
"(": ")",
"{": "}"
}[stack[stack.length - 1]]
? [stack.slice(0, -1), closeChar]
: [stack, [...closeChar, char]],
[[], []]
)
.every(array => array.length === 0);
``````

Cheers!