Home > Software engineering >  Reset loop with condition
Reset loop with condition

Time:12-03

I'm coding project with codewars and have a trouble. This function has to check if parentheses in string are valid. My problem is when i assign i = 0 in function valid pair it's doesnt work . I tried assign it below if statement and then my loop is infinite. My idea is valid pairs and then start over and over while parens.lenght will be <= 2 then i know that there left a pair and i can nothing to do with it. Could you help me?

// "()"              =>  true
// ")(()))"          =>  false
// "("               =>  false
// "(())((()())())"  =>  true
const validPair = (parens) => {
    console.log(parens);

    for (let i = 0; i < parens.length; i  ) {
        if (parens[i] == '(' && parens[i   1] == ')') {
            parens.splice(i, 2);
            i = 0;
            console.log(parens.length);
        }

        if (parens.length <= 2) {
            console.log(parens);
        }
    }
    console.log(parens);
};

function validParentheses(parens) {
    let validLength = 0;

    parens = parens.split('');

    parens.forEach((el) => {
        if (el == '(') {
            validLength  ;
        } else {
            validLength--;
        }
    });
    if (validLength != 0) {
        return false;
    } else {
        validPair(parens);
    }
}

console.log(validParentheses('(()))(()'));

I will be updating this code but i stuck in this moment and dont know what to do.

CodePudding user response:

You've overcomplicated things

Simply counting is enough

// "()"              =>  true
// ")(()))"          =>  false
// "("               =>  false
// "(())((()())())"  =>  true
function validParentheses(parens) {
  let lefts = 0
  for (const par of parens) {
    if (par === '(') {
      lefts  = 1
    } else {
      lefts -= 1
    }
    if (lefts < 0) return false
  }
  if (lefts !== 0) return false
  return true
}

console.log(validParentheses('()'));
console.log(validParentheses('(()))(()'));
console.log(validParentheses('('));
console.log(validParentheses('(())((()())())'));

CodePudding user response:

Approach:

The idea is to use stack. so when you get ( you need to push it to stack and when you get ) you need to pop it. And at the end just need to check stack is still empty or not. if stack is empty that means parentheses are valid.

Edge case:

When there's no element in the stack and you have ) that means there's no ( bracket to match with it. so it returns false.

const validParentheses = (str) => {
    const stack = [];

  for (let parentheses of str) {
    if (parentheses == '(') stack.push(parentheses);
    else {
      if (!stack.length) return false;
      stack.pop();
    }
  }
  return !stack.length;
}

console.log(validParentheses("()"));     
console.log(validParentheses(")(()))"));  
console.log(validParentheses("("));             
console.log(validParentheses("(())((()())())"));

  • Related