Longitud máxima de string equilibrada después de intercambiar y eliminar caracteres

Dada una string str que consta de los caracteres ‘(‘ , ‘)’ , ‘[‘ , ‘]’ , ‘{‘ y ‘}’ únicamente. La tarea es encontrar la longitud máxima de la string equilibrada después de eliminar cualquier carácter e intercambiar dos caracteres adyacentes.
Ejemplos: 
 

Entrada: str = “))[]]((” 
Salida:
La string se puede convertir a()[]()
Entrada: str = “{{{{{{{}” 
Salida:
 

Enfoque: la idea es eliminar los paréntesis no coincidentes adicionales de la string porque no podemos generar un par equilibrado para ella e intercambiar los caracteres restantes para equilibrar la string. Por lo tanto, la respuesta es igual suma de pares de todos los paréntesis equilibrados. Tenga en cuenta que podemos mover un personaje a cualquier otro lugar mediante intercambios adyacentes.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// 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;
}

Java

// 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.

Python3

# 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

C#

// 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.

PHP

<?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.

Javascript

<script>
 
// Javascript implementation of the approach   
// Function to return the length of
    // the longest balanced sub-string
    function maxBalancedStr( s) {
 
        // To store the count of parentheses
        var open1 = 0, close1 = 0;
        var open2 = 0, close2 = 0;
        var open3 = 0, close3 = 0;
 
        // Traversing the string
        for (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
        var maxLen = 2 * Math.min(open1, close1)
        + 2 * Math.min(open2, close2)
        + 2 * Math.min(open3, close3);
 
        return maxLen;
    }
 
    // Driven code
     
        var s = "))[]]((";
        document.write(maxBalancedStr(s));
 
// This code contributed by gauravrajput1
 
</script>
Producción: 

6

 

Publicación traducida automáticamente

Artículo escrito por Sairahul Jella y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *