DEV Community

duccanhole
duccanhole

Posted on

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;
};
Enter fullscreen mode Exit fullscreen mode

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

Discussion (5)

Collapse
frankwisniewski profile image
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('[({)(})[]{}]'))
Enter fullscreen mode Exit fullscreen mode
Collapse
coderduck profile image
duccanhole Author

Are you use regex? It's cool !

Collapse
frankwisniewski profile image
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('[({)(})[]{}]'))
Enter fullscreen mode Exit fullscreen mode
Collapse
lukeshiru profile image
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 = {
    "[": "]",
    "(": ")",
    "{": "}"
};
Enter fullscreen mode Exit fullscreen mode
  • 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;
Enter fullscreen mode Exit fullscreen mode

With this:

return stack.length === 0 && closeChar.length === 0;
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
coderduck profile image
duccanhole Author

many thanks