
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Length of Balanced String After Swapping and Removal of Characters in C++
We are given a string containing (,),{,},[,] characters only. The goal is to find the maximum length of such string so that it becomes balanced by swapping adjacent characters or removing a character. We will do this by comparing adjacent characters, if they are opposite of each other then they can be swapped. ( }{,)(,][ can be swapped, while {{,)),[[,}},)),]] cannot be swapped ).
Also if a character has no matching pair, then it can be removed also. ( “{{}][“, here first { can be removed and balanced string length becomes 4 )
Input
str[]= “ {{{}}{]]][()” length 12
Output
Maximum length of balances string: 8
Explanation − str[0] and str[1] cannot be swapped, remove str[0]= “{{}}{]]][()” Original str[1] and str[2] cannot be swapped, remove str[1]= “{}}{]]][()” {} are balanced }{ can be swapped, remove next 2 ]], swap ][ and () are also balanced Final string is {}{}[](). Length is 8.
Input
str[]= “(((((()” length 7
Output
str[]= “(((((()” length 7
Explanation − Only str[5] and str[6] are balanced, remove all. Final string (). Length is 2
Approach used in the below program is as follows
Character array str[] stores the original string. Integer Length stores the length of the string.
Function maxBalancedStr (char str[], int len) takes the string and its length as parameters and returns the maximum length of the balanced string.
Variable count is used to store the length of such string, initially 0.
Start traversing the string from the first character and check if adjacent character can be swapped to make both of them balanced. Or if they are already balanced, increase count by 2.
Do this for pairs like, (),)( and {},}{ and [],][, increment i also if such pairs exist, to move to the next character.
In the end the count stores the length of the balanced string.
Return count as result.
Example
// 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(char str[20], int len){ int count=0; // Traversing the string for (int i = 0; i <len;i++) { // Check type of parentheses and // incrementing count for it if((str[i]=='(' && str[i+1]==')') || (str[i]==')' && str[i+1]=='(')) //can swap{ count+=2; ++i; } else if((str[i]=='{' && str[i+1]=='}') || (str[i]=='}' && str[i+1]=='{')) //can swap{ count+=2; ++i; } else if((str[i]=='[' && str[i+1]==']') || (str[i]==']' && str[i+1]=='[')) //can swap count+=2; ++i; } } return count; } // Driven code int main(){ char str[] = ")([]](("; int length=7; cout << maxBalancedStr(str,length); return 0; }
Output
4