Maximum length of balanced string after swapping and removal of characters

Given a string str consisting of characters ‘(‘, ‘)’, ‘[‘, ‘]’, ‘{‘ and ‘}’ only. The task is to find the maximum length of the balanced string after removing any character and swapping any two adjacent characters.

Examples:

Input: str = “))[]]((”
Output: 6
The string can be converted to ()[]()

Input: str = “{{{{{{{}”
Output: 2



Approach: The idea is to remove extra unmatched parentheses from string because we cannot generate a balanced pair for it and swap the remaining characters to balance the string. Therefore the answer is equal summation of pairs of all balanced parenthesis. Note that we can move a character to any other place by adjacent swappings.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the length of
// the longest balanced sub-string
int maxBalancedStr(string s)
{
  
    // To store the count of parentheses
    int open1 = 0, close1 = 0;
    int open2 = 0, close2 = 0;
    int open3 = 0, close3 = 0;
  
    // Traversing the string
    for (int i = 0; i < s.length(); i++) {
  
        // Check type of parentheses and
        // incrementing count for it
        switch (s[i]) {
        case '(':
            open1++;
            break;
        case ')':
            close1++;
            break;
        case '{':
            open2++;
            break;
        case '}':
            close2++;
            break;
        case '[':
            open3++;
            break;
        case ']':
            close3++;
            break;
        }
    }
  
    // Sum all pair of balanced parentheses
    int maxLen = 2 * min(open1, close1)
                 + 2 * min(open2, close2)
                 + 2 * min(open3, close3);
  
    return maxLen;
}
  
// Driven code
int main()
{
    string s = "))[]]((";
    cout << maxBalancedStr(s);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
class GFG
{
      
// Function to return the length of
// the longest balanced sub-string
static int maxBalancedStr(String s)
{
  
    // To store the count of parentheses
    int open1 = 0, close1 = 0;
    int open2 = 0, close2 = 0;
    int open3 = 0, close3 = 0;
  
    // Traversing the string
    for (int i = 0; i < s.length(); i++)
    {
  
        // Check type of parentheses and
        // incrementing count for it
        switch (s.charAt(i)) 
        {
        case '(':
            open1++;
            break;
        case ')':
            close1++;
            break;
        case '{':
            open2++;
            break;
        case '}':
            close2++;
            break;
        case '[':
            open3++;
            break;
        case ']':
            close3++;
            break;
        }
    }
  
    // Sum all pair of balanced parentheses
    int maxLen = 2 * Math.min(open1, close1)
                + 2 * Math.min(open2, close2)
                + 2 * Math.min(open3, close3);
  
    return maxLen;
}
  
// Driven code
public static void main(String[] args)
{
    String s = "))[]]((";
    System.out.println(maxBalancedStr(s));
}
}
  
// This code is contributed by Code_Mech.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of the approach
  
# Function to return the length of
# the longest balanced sub-string
def maxBalancedStr(s):
      
    # To store the count of parentheses
    open1 = 0
    close1 = 0
    open2 = 0
    close2 = 0
    open3 = 0
    close3 = 0
  
    # Traversing the string
    for i in range(len(s)):
          
        # Check type of parentheses and
        # incrementing count for it
        if(s[i] == '('):
            open1 += 1
            continue
        if s[i] == ')':
            close1 += 1
            continue
        if s[i] == '{':
            open2 += 1
            continue
        if s[i] == '}':
            close2 += 1
            continue
        if s[i] == '[':
            open3 += 1
            continue
        if s[i] == ']':
            close3 += 1
            continue
  
    # Sum all pair of balanced parentheses
    maxLen = (2 * min(open1, close1) + 
              2 * min(open2, close2) + 
              2 * min(open3, close3))
  
    return maxLen
  
# Driven code
if __name__ == '__main__':
    s = "))[]](("
    print(maxBalancedStr(s))
  
# This code is contributed by
# Surendra_Gangwar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
  
class GFG
{
      
// Function to return the length of
// the longest balanced sub-string
static int maxBalancedStr(string s)
{
  
    // To store the count of parentheses
    int open1 = 0, close1 = 0;
    int open2 = 0, close2 = 0;
    int open3 = 0, close3 = 0;
  
    // Traversing the string
    for (int i = 0; i < s.Length; i++)
    {
  
        // Check type of parentheses and
        // incrementing count for it
        switch (s[i]) 
        {
        case '(':
            open1++;
            break;
        case ')':
            close1++;
            break;
        case '{':
            open2++;
            break;
        case '}':
            close2++;
            break;
        case '[':
            open3++;
            break;
        case ']':
            close3++;
            break;
        }
    }
  
    // Sum all pair of balanced parentheses
    int maxLen = 2 * Math.Min(open1, close1)
                + 2 * Math.Min(open2, close2)
                + 2 * Math.Min(open3, close3);
  
    return maxLen;
}
  
// Driver code
public static void Main()
{
    string s = "))[]]((";
    Console.WriteLine(maxBalancedStr(s));
}
}
  
// This code is contributed by Code_Mech.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implementation of the approach
// Function to return the length of
// the longest balanced sub-string
 function maxBalancedStr($s)
{
  
    // To store the count of parentheses
    $open1 = 0; $close1 = 0;
    $open2 = 0; $close2 = 0;
    $open3 = 0; $close3 = 0;
  
    // Traversing the string
    for ($i = 0; $i < strlen($s); $i++)
    {
  
        // Check type of parentheses and
        // incrementing count for it
        switch ($s[$i]) 
        {
        case '(':
            $open1++;
            break;
        case ')':
            $close1++;
            break;
        case '{':
            $open2++;
            break;
        case '}':
            $close2++;
            break;
        case '[':
            $open3++;
            break;
        case ']':
            $close3++;
            break;
        }
    }
  
    // Sum all pair of balanced parentheses
    $maxLen = 2 * min($open1, $close1)
                + 2 * min($open2, $close2)
                + 2 * min($open3, $close3);
  
    return $maxLen;
}
  
// Driven code
{
    $s = "))[]]((";
    echo(maxBalancedStr($s));
}
  
// This code is contributed by Code_Mech.

chevron_right


Output:

6


My Personal Notes arrow_drop_up

Always try to improve and willing to learn

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.