code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

03 Balance Parentheses

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

function peek(stack) {
  return stack[stack.length - 1]
}

function balanceParentheses(str) {
  let stack = []
  for (let index = 0; index < str.length; index++) {
    const letter = str.charAt(index)
    if (letter === '(') {
      stack.push(letter)
    } else if (letter === ')') {
      if (stack.length === 0) {
        return false
      } else if (peek(stack) === '(') {
        stack.pop()
      } else {
        return false
      }
    }
  }
  return stack.length === 0
}

test.only('balance Parentheses', () => {
  expect(balanceParentheses('({Ashish})')).toEqual(true)
  expect(balanceParentheses('()')).toEqual(true)
  expect(balanceParentheses('(())')).toEqual(true)
  expect(balanceParentheses('((()))')).toEqual(true)
  expect(balanceParentheses('(')).toEqual(false)
  expect(balanceParentheses(')')).toEqual(false)
  expect(balanceParentheses(')(')).toEqual(false)
  expect(balanceParentheses('(()')).toEqual(false)
})

Created 2019-11-30T02:13:21+05:30, updated 2019-11-30T17:46:30+05:30 · History · Edit