How to check that string has equal number of this "(" and which is preceded by a corresponding ")" in JavaScript

Viewed 55

/* I have tried this I get an equal number of "(" count but I don't how to check that it is preceded by a corresponding or not*/

        function checkStr(str)
    {
        len = str.length;
        let count =0;
        let count1=0;
        for(let i=0; i<=len;i++)
    {
            if(str[i]==')')
    {
                count++;
    }
    else if(str[i]=='(')
   {
        count1++;
    }
    
    }
        if(count==count1)
    {
            return true;
    }
        else{
            return false;
    
    }
    }
    let result=checkStr("))a+b((");
    console.log(result)

output 
should be false but I'm getting True 
2 Answers

I would use a stack for this use case in order to keep the state of opening/closing parentheses.

checkStr = str => {
  const stack = [];
  for (let i = 0; i < str.length; i++){
  const current = str[i];
    if (current !== "(" && current !== ")"){
     continue;
    }
    if (current === "("){
      stack.push(current);
    }
    else if (stack[stack.length - 1] === "("){
       stack.pop();
    }
    else{
        return false;
    }
  }
  return stack.length ? false : true;
}

console.log(checkStr("(d(s)")); // false
console.log(checkStr("(d(s))")); // true
console.log(checkStr("))a+b((")); // false

So off my head on my phone. I could approach it like this.

I would create a temporary string that stores ( e.g called it left bracket I would also create another that stores ) e.g call it right bracket

So I will iterate through the parent string and see if I find a character that is left bracket I append it to left bracket variable when I find a character that’s right bracket I append it to right bracket string .

I will then compare the string length if they match then it satisfies my conditions.

let parentString  = “(hello world) and (I am here)”;
    let leftbracket = “”;
    let rightbracket = “”; 
    for (let char of parentString) {
      if(char === ‘(‘){
    leftbracket = leftbracket.concat(char);
    }
    if(char === ‘)’){
    rightbracket = rightbracket.concat(char);
    }
    }
    
    if (leftbracket.length === rightbracket.length){
     console.log(‘true’);
    }
    else{
    console.log(‘false’);
    }

Note: I answered this on my phone so pardon any typos or error but it should work or give you an idea.

Related