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 = 0, c1 = 0, o2 = 0, c2 = 0, o3 = 0, c3 = 0;
    for (int i = 0; i < 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(c1, o1) * 2 + min(c2, o2) * 2 + 
min(c3, o3) * 2;
    return res;
}
int main()
{

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

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

    return 0;
}


No comments:

Post a Comment