Bracket sequences

A bracket sequence is a string that contains only characters '(' and ')'.

A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences '()()' and '(())' are correct. The resulting expressions of these sequences are: '(1)+(1)' and '((1+1)+1)'. However, '(', ')(', and '(' are incorrect bracket sequences. 

You are given a bracket sequence s(s1s2...sn), where si denotes the type of i's a bracket (open or close). It is not mandatory that s is necessarily correct. Your task is to determine the number of i's such that sisi+1...sns1s2...si1 is a correct bracket sequence.

Example:

Input:  s = ")()()("
Output: 3

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int bracketSequences(string s)
{
    int n = s.size();
    int cnt = 0;
    int l = 0;
    for (int i = 0i < ni++)
    {
        if (s[i] == '(')
            l++;
    }
    int r = n - l;
    if (l != r)
        return 0;
    else
    {
        l = 0;
        int x = 0y = 0;
        for (int i = 0i < ni++)
        {
            if (s[i] == '(')
                l++;
            else
                l--;
            if (l < y)
            {
                y = l;
                x = i + 1;
            }
        }
        reverse(s.begin(), s.begin() + x);
        reverse(s.begin() + xs.end());
        reverse(s.begin(), s.end());
        l = 0;
        for (int i = 0i < ni++)
        {
            if (s[i] == '(')
                l++;
            else
                l--;
            if (l == 0)
                cnt++;
        }
        return cnt;
    }
}
int main()
{

    string s = ")()()(";

    cout << bracketSequences(s<< "\n";

    return 0;
}


No comments:

Post a Comment