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.

Top comments (4)

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

Are you use regex? It's cool !

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

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
 
coderduck profile image
duccanhole

many thanks