1

I am trying to solve the problem of whether the parentheses in the array are closed correctly or not. For example, if two pairs of parentheses are closed correctly, there are two cases: "()()" "(())". I want to first find the number of all cases of 2 pairs of parentheses, and then verify that it is closed correctly or not.

What I'm thinking is that when I try to find 2 pairs, first of all, "(", "(", ")", ")" is to make all cases first with 2 open and 2 closed parentheses. How can I get all the cases with 2 open parentheses + 2 closed parentheses? Please help me.

김민식
  • 87
  • 4
  • 2
    For example use a *retain* counter. Increment it on `(` and decrement it on `)`. If it's 0 everything is fine. If it's positive or negative it indicates the number of missing parenthesis respectively. – vadian Nov 18 '20 at 08:13
  • 1
    Compare https://stackoverflow.com/q/54222503/1187415. – Martin R Nov 18 '20 at 09:27

1 Answers1

0

In pseudo code:

unClosedCounter = 0

For char in string{
    if char == "("
    {
        unClosedCounter++
    }

    if char ==  ")"{
        if unClosedCounter == 0
        {
            return false
        }

        unClosedCounter--
    }
}

Return unClosedCounter == 0
Arik Segal
  • 2,523
  • 10
  • 26