Compruebe si la profundidad de los paréntesis es correcta en la string dada

Dada una string S que consta de paréntesis de apertura, paréntesis de cierre y números enteros, la tarea es imprimir Sí si, en esta string, los números enteros indican correctamente su profundidad. La profundidad se refiere al número de conjuntos anidados de paréntesis que rodean ese número entero. Imprima No de lo contrario.
Ejemplos: 
 

Entrada: S = “((2)((3)))” 
Salida: Sí 
Explicación: 
Número de paréntesis de apertura y cierre alrededor de 2 = 2 
Número de paréntesis de apertura y cierre alrededor de 3 = 3 
Entrada: S = “((35) (2))” 
Salida: No 
Explicación: 
Número de paréntesis de apertura y cierre alrededor de 35 = 2 
Número de paréntesis de apertura y cierre alrededor de 2 = 2 
 

Acercarse: 
 

  1. Iterar la string carácter por carácter
  2. Si está abriendo o cerrando paréntesis, agregue a una array arr[]
  3. Si el carácter es un dígito, itere hasta que se lea el número completo y luego agréguelo al arr[]
  4. Iterar la array arr[] elemento por elemento 
    • Si el elemento es ‘(‘ incrementa la profundidad y abre en 1
    • Si el elemento es ‘)’, disminuya la profundidad en 1 e incremente cerca de 1
    • Si el elemento es un número entero, verifique si «Entero! = profundidad», si es verdadero, 
      establezca el indicador en 0 y rompa el ciclo
  5. Después de iterar toda la string, verifique si abrir no es igual a cerrar, si es cierto, establezca la bandera = 0

A continuación se muestra la implementación del enfoque anterior. 
 

C++

// Function to check if the Depth
// of Parentheses is correct
// in the given String
 
#include <bits/stdc++.h>
using namespace std;
 
bool Formatted(string s)
{
    vector<char> k;
    int i = 0;
 
    while (i < s.size())
    {
        // Appending if the
        // Character is not integer
        if (s[i]==')' or s[i]=='(')
        {
            k.push_back(s[i]);
            i += 1;
        }
        else
        {
            // Iterating till the entire
            // Digit is read
            char st;
            while (s[i]!=')' and s[i]!=')')
            {
                st = s[i];
                i = i + 1;
            }
            k.push_back(st);
        }
    }
 
    int depth = 0, flag = 1;
    int open = 0, close = 0;
 
    for (char i:k)
    {
 
        // Check if character is '('
        if (i == '(')
        {
            // Increment depth by 1
            depth += 1;
 
            // Increment open by 1
            open += 1;
 
        // Check if character is ')'
    }else if (i == ')'){
 
            // Decrement depth by 1
            depth -= 1;
 
            // Increment close by 1
            close += 1;
        }
        else{
            if (i-'0' != depth){
                flag = 0;
                break;
            }
        }
    }
 
    // Check if open parentheses
    // NOT equals close parentheses
    if (open != close)
        flag = 0;
 
    return (flag == 1)?true:false;
}
 
// Driver Code
int main()
{
    string s = "((2)((3)))";
    bool k = Formatted(s);
    if (k == true)
        printf("Yes");
    else
        printf("No");
    return 0;
}
 
// This code is contributed by mohit kumar 29

Java

// Function to check if the Depth
// of Parentheses is correct
// in the given String
import java.util.*;
 
class GFG{
 
static boolean Formatted(String s)
{
    Vector<Character> k = new Vector<Character>();
    int i = 0;
 
    while (i < s.length())
    {
        // Appending if the
        // Character is not integer
        if (s.charAt(i)==')' || s.charAt(i)=='(')
        {
            k.add(s.charAt(i));
            i += 1;
        }
        else
        {
            // Iterating till the entire
            // Digit is read
            char st = 0;
            while (s.charAt(i)!=')' && s.charAt(i)!=')')
            {
                st = s.charAt(i);
                i = i + 1;
            }
            k.add(st);
        }
    }
 
    int depth = 0, flag = 1;
    int open = 0, close = 0;
 
    for (char i2 : k)
    {
 
        // Check if character is '('
        if (i2 == '(')
        {
            // Increment depth by 1
            depth += 1;
 
            // Increment open by 1
            open += 1;
 
        // Check if character is ')'
    }else if (i2 == ')'){
 
            // Decrement depth by 1
            depth -= 1;
 
            // Increment close by 1
            close += 1;
        }
        else{
            if (i2-'0' != depth){
                flag = 0;
                break;
            }
        }
    }
 
    // Check if open parentheses
    // NOT equals close parentheses
    if (open != close)
        flag = 0;
 
    return (flag == 1)?true:false;
}
 
// Driver Code
public static void main(String[] args)
{
    String s = "((2)((3)))";
    boolean k = Formatted(s);
    if (k == true)
        System.out.printf("Yes");
    else
        System.out.printf("No");
}
}
 
// This code is contributed by Rajput-Ji

Python3

# Function to check if the Depth
# of Parentheses is correct
# in the given String
 
def Formatted(s):
    k = []
    i = 0
 
    while i < len(s):
 
        # Appending if the
        # Character is not integer
        if s[i].isdigit() == False:
 
            k.append(s[i])
            i += 1
        else:
 
            # Iterating till the entire
            # Digit is read
            st = ""
            while s[i].isdigit():
                st += s[i]
                i = i + 1
            k.append(int(st))
 
    depth, flag = 0, 1
    open, close = 0, 0
 
    for i in k:
 
        # Check if character is '('
        if i == '(':
 
            # Increment depth by 1
            depth += 1
 
            # Increment open by 1
            open += 1
 
        # Check if character is ')'
        elif i == ')':
 
            # Decrement depth by 1
            depth -= 1
 
            # Increment close by 1
            close += 1
        else:
            if i != depth:
                flag = 0
                break
 
    # Check if open parentheses
    # NOT equals close parentheses
    if open != close:
        flag = 0
 
    return True if flag == 1 else False
 
# Driver Code
if __name__ == '__main__':
    s = '((2)((3)))'
    k = Formatted(s)
    if k == True:
        print("Yes")
    else:
        print("No")

C#

// Function to check if the Depth
// of Parentheses is correct
// in the given String
using System;
using System.Collections.Generic;
 
class GFG
{
 
static bool Formatted(String s)
{
    List<char> k = new List<char>();
    int i = 0;
 
    while (i < s.Length)
    {
        // Appending if the
        // char is not integer
        if (s[i]==')' || s[i]=='(')
        {
            k.Add(s[i]);
            i += 1;
        }
        else
        {
            // Iterating till the entire
            // Digit is read
            char st = '\x0000';
            while (s[i] != ')' && s[i] != ')')
            {
                st = s[i];
                i = i + 1;
            }
            k.Add(st);
        }
    }
 
    int depth = 0, flag = 1;
    int open = 0, close = 0;
 
    foreach (char i2 in k)
    {
 
        // Check if character is '('
        if (i2 == '(')
        {
            // Increment depth by 1
            depth += 1;
 
            // Increment open by 1
            open += 1;
 
        // Check if character is ')'
    }else if (i2 == ')'){
 
            // Decrement depth by 1
            depth -= 1;
 
            // Increment close by 1
            close += 1;
        }
        else{
            if (i2-'0' != depth){
                flag = 0;
                break;
            }
        }
    }
 
    // Check if open parentheses
    // NOT equals close parentheses
    if (open != close)
        flag = 0;
 
    return (flag == 1)?true:false;
}
 
// Driver Code
public static void Main(String[] args)
{
    String s = "((2)((3)))";
    bool k = Formatted(s);
    if (k == true)
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// Function to check if the Depth
// of Parentheses is correct
// in the given String
function Formatted(s)
{
    let k = [];
    let i = 0;
   
    while (i < s.length)
    {
        // Appending if the
        // Character is not integer
        if (s[i]==')' || s[i]=='(')
        {
            k.push(s[i]);
            i += 1;
        }
        else
        {
            // Iterating till the entire
            // Digit is read
            let st = 0;
            while (s[i]!=')' && s[i]!=')')
            {
                st = s[i];
                i = i + 1;
            }
            k.push(st);
        }
    }
   
    let depth = 0, flag = 1;
    let open = 0, close = 0;
   
    for (let i2=0;i2< k.length;i2++)
    {
   
        // Check if character is '('
        if (k[i2] == '(')
        {
            // Increment depth by 1
            depth += 1;
   
            // Increment open by 1
            open += 1;
   
        // Check if character is ')'
    }else if (k[i2] == ')'){
   
            // Decrement depth by 1
            depth -= 1;
   
            // Increment close by 1
            close += 1;
        }
        else{
            if (k[i2]-'0' != depth){
                flag = 0;
                break;
            }
        }
    }
   
    // Check if open parentheses
    // NOT equals close parentheses
    if (open != close)
        flag = 0;
   
    return (flag == 1)?true:false;
}
 
// Driver Code
let s = "((2)((3)))";
let k = Formatted(s);
if (k == true)
    document.write("Yes");
else
    document.write("No");
 
 
// This code is contributed by patel2127
</script>
Producción: 

Yes

 

Publicación traducida automáticamente

Artículo escrito por imran_shaik 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 *