Skip to content

string[index] doesn't work correctly #16

@ngocdaothanh

Description

@ngocdaothanh

See the line console.log(string, i, char) below in the program to check if parentheses are balanced:

function check(string) {
  let count = 0

  for (let i = 0; i < string.length; i++) {
    const char = string[i]
    console.log(string, i, char)

    if (char === '(')
      count++
    else if (char === ')')
      count--

    console.log(count)
    if (count < 0) return false
  }

  return count === 0
}

console.log(check('()(()())'))

Expected output:

()(()()) 0 (
()(()()) 1 )
()(()()) 2 (
...

Actual output:

()(()()) 0 (
()(()()) 1 (
()(()()) 2 (
...

It seems that in this program string[index] always returns the first character.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions