Checking string has balanced parentheses

后端 未结 18 2336
谎友^
谎友^ 2020-12-01 08:42

I am reading the Algorithm Design Manual Second Edition and this is from an exercise question. Quoting the question

A common problem for comp

18条回答
  •  情深已故
    2020-12-01 08:55

    using System;
    class Solution
    {
        public int solution(string S)
        {
            int x1 = 0;
            int x2 = 0;
            for (int i = 0; i < S.Length; i++)
            {
                if (S[i] == ')')
                    if (x1 <= 0) return 0;
                    else x1--;
                else if (S[i] == '(')
                    x1++;
            }
            if (x1 == 0)
                return 1;
            else
                return 0;
        }
    }
    

提交回复
热议问题