Largest Balanced String

1. An empty sequence is balanced.

2. A sequence of the form (A) or [A] or {A} is balanced if A is balanced.

3. A sequence of the form AB is balanced if A and B both are balanced.

You are given a string A, consisting of '(', ')', '[', ']', '{' and '}' only. You have to find the maximum length of the balanced string after performing some valid operation(s).

Valid operations are

1. Remove any character from string A

2. Swap any two adjacent characters of string A

You can perform these valid operations in any order and any number of times.

Example:

Input:  s = "))[]](("
Output: 6

Approach

C++

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

int largestBalancedString(string s)
{

    int o1 = 0c1 = 0o2 = 0c2 = 0o3 = 0c3 = 0;
    for (int i = 0i < s.size(); i++)
    {
        if (s[i] == '(')
            o1++;
        else if (s[i] == ')')
            c1++;
        else if (s[i] == '{')
            o2++;
        else if (s[i] == '}')
            c2++;
        else if (s[i] == '[')
            o3++;
        else
            c3++;
    }
    int res = min(c1o1) * 2 + min(c2o2) * 2 + 
min(c3o3) * 2;
    return res;
}
int main()
{

    string s = "))[]]((";

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

    return 0;
}


No comments:

Post a Comment