Introducción

1

¿Ya tomaste el Curso Avanzado de Algoritmos: Patrones de Arrays y Strings?

Lista Enlazada

2

Estructura de datos: Lista Enlazada

3

Programando listas enlazadas con Java

4

Cómo Invertir una Lista Enlazada

5

Odd Even Linked List: análisis del problema

6

Solución de Odd Even Linked List

7

Playground: Odd Even Liked List

8

Programando Odd Even Linked List con C++

9

Linked List Cycle: análisis del problema

10

Solución de Linked List Cycle

11

Playground: Linked List Cycle

12

Programando Linked List Cycle con Python

13

Palindrome Linked List: análisis del problema

14

Solución de Palindrome Linked List

15

Playground: Palindrome Linked List

16

Programando Palindrome Linked List con Java

17

Reorder List: análisis del problema

18

Solución de Reorder List

19

Programando Reorder List con JavaScript

20

Playground: Reorder List Without Repeated Values

21

Reto: LRU Caché

22

Ejercicios Prácticos con Listas Enlazadas y Historial de Navegador

23

Operaciones con Listas Enlazadas: Suma, Intercambio y Navegador

Pilas y colas

24

Estructura de datos: Pilas y Colas

25

Paréntesis Válido: análisis del problema

26

Solución de Paréntesis Válido

27

Playground: Paréntesis Válido

28

Programando Paréntesis Válido con C++

29

Comparación de Cadenas con Backspaces

Colas de prioridad

30

Estructura de datos: Colas de Prioridad

31

K Closest Points to Origin: análisis del problema

32

Solución de K Closest Points to Origin

33

Playground: K Closest Points to Origin

34

Programando K Closest Points to Origin con Python

35

Reorganize String: análisis del problema

36

Solución de Reorganize String

37

Playground: Reorganize String

38

Programando Reorganize String con Python

39

Colas de Prioridad: Ejercicios Prácticos y Soluciones

40

Colas de Prioridad y Gestión de Eventos

Próximos pasos

41

Toma el Curso Avanzado de Algoritmos: Grafos y Árboles

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Solución de Paréntesis Válido

26/41
Recursos

Aportes 11

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

def isValid(s):
    pila=0
    for i in s:
        if i=='(':
          pila+=1
        elif i==')':
           pila-=1
        if pila<0:
           return False  
    return pila==0

isValid('(()))')

Implementado con stacks como Linked List, pero el complex en el espacio sigue O(n)


Y sin usar Linked List, el espacio O(1), pero si aumenta la complejidad del ejercicio si creeria que es mejor con stacks como Linked List:

```python def check_parentesis(case:str)->bool: #Create the stack new_stack = Stack() for i in case: new_stack.append(i) # iterate over the stack and chase '(' or ')'on it prev = new_stack.top current = prev.next check = Stack() flag = 0 flag2 = 0 while prev and prev.next: if prev and prev.data == ')': check.append(prev) flag += 1 if current and current.data == '(': check.append(current) flag2 += 1 prev = prev.next current = current.next if flag and flag2 > 0 and flag == flag2: return True else: return False ```def check\_parentesis(case:str)->bool:    #Create the stack     new\_stack = Stack()    for i in case:        new\_stack.append(i)    # iterate over the stack and chase '(' or ')'on it    prev = new\_stack.top    current = prev.next    check = Stack()    flag = 0    flag2 = 0    while prev and prev.next:        if prev and prev.data == ')':            check.append(prev)            flag += 1        if current and current.data == '(':            check.append(current)            flag2 += 1         prev = prev.next        current = current.next    if flag and flag2 > 0 and flag == flag2:        return True    else:        return False
Mi solución sin utilizar pilas en C++ ```cpp int parentesis=0; std::string texto; std::cin>>texto; for (int i = 0; i < texto.length(); ++i) { if (texto\[i]=='('){ parentesis++; }else if (texto\[i]==')'){ parentesis--; }else continue; } if (parentesis==0){ std::cout<<"Hay correcto orden de parentesis"<\
```python def valid_parentheses(input: str): print(f"checking {input=}") stack = [] for elem in input: if elem == '(': stack.append(elem) elif elem == ')': if len(stack) != 0 and stack[-1] == '(': stack.pop() else: return "No valid" elif elem.isalpha() or elem.isnum(): continue if len(stack) != 0: return "No valid" return "Valid" print(valid_parentheses("()")) print(valid_parentheses("(()))")) print(valid_parentheses("(")) print(valid_parentheses(")")) print(valid_parentheses(")(")) print(valid_parentheses("(caracoles)(decolores)()")) ```def valid\_parentheses(input: str): print(f"checking {input=}") stack = \[] for elem in input: if elem == '(': stack.append(elem) elif elem == ')': if len(stack) != 0 and stack\[-1] == '(': stack.pop() else: return "No valid" elif elem.isalpha() or elem.isnum(): continue if len(stack) != 0: return "No valid" return "Valid" print(valid\_parentheses("()")) print(valid\_parentheses("(()))")) print(valid\_parentheses("(")) print(valid\_parentheses(")")) print(valid\_parentheses(")(")) print(valid\_parentheses("(caracoles)(decolores)()"))
```python #!/usr/bin/env python3 """Check for valid or balanced parentheses""" size = 50 stack = ['' for _ in range(size)] top = -1 def push(ch: str) -> None: """Push ch into stack""" global top if top == size-1: return else: top += 1 stack[top] = ch def pop() -> int: """Pop off the top data in the stack""" global top if top == -1: return -1 else: data = stack[top] top -= 1 return data def isStackEmpty() -> bool: """Check if stack is empty""" if (top == -1): return True else: return False def isStackFull() -> bool: """Check if stack is full""" if (top == size-1): return True else: return False def isBalanced(str: str) -> bool: """Check if parenthese is valid""" for ch in str: if (ch == '(' or ch == '[' or ch == '{'): push(ch) else: if isStackEmpty(): return False top = pop() if ((ch == ')' and top != '(') or (ch == ']' and top != '[') or (ch == '}' and top != '{')): return False return isStackEmpty() def isValid(str: strg) -> bool: """Check if parenthese is valid""" parentheses = {'(':')', '[':']', '{':'}'} stack = [] for ch in strg: if (ch in parentheses.keys()): stack.append(ch) else: if stack == []: return False top = stack.pop() if ch != parentheses[top]: return False return stack == [] if __name__ == '__main__': parentheses = input("Enter parentheses to test\n").strip() if (isBalanced(parentheses)): print("Valid parentheses") else: print("Oops! Invalid parentheses") if (isBalanced(parentheses)): print("Valid parentheses") else: print("Oops! Invalid parentheses") ```#!/usr/bin/env python3 """Check for valid or balanced parentheses""" size = 50 stack = \['' for \_ in range(size)] top = -1 def push(ch: str) -> None: """Push ch into stack""" global top if top == size-1: return else: top += 1 stack\[top] = ch def pop() -> int: """Pop off the top data in the stack""" global top if top == -1: return -1 else: data = stack\[top] top -= 1 return data def isStackEmpty() -> bool: """Check if stack is empty""" if (top == -1): return True else: return False def isStackFull() -> bool: """Check if stack is full""" if (top == size-1): return True else: return False def isBalanced(str: str) -> bool: """Check if parenthese is valid""" for ch in str: if (ch == '(' or ch == '\[' or ch == '{'): push(ch) else: if isStackEmpty(): return False top = pop() if ((ch == ')' and top != '(') or (ch == ']' and top != '\[') or (ch == '}' and top != '{')): return False return isStackEmpty() def isValid(str: strg) -> bool: """Check if parenthese is valid""" parentheses = {'(':')', '\[':']', '{':'}'} stack = \[] for ch in strg: if (ch in parentheses.keys()): stack.append(ch) else: if stack == \[]: return False top = stack.pop() if ch != parentheses\[top]: return False return stack == \[] if \_\_name\_\_ == '\_\_main\_\_': parentheses = input("Enter parentheses to test\n").strip() if (isBalanced(parentheses)): print("Valid parentheses") else: print("Oops! Invalid parentheses") if (isBalanced(parentheses)): print("Valid parentheses") else: print("Oops! Invalid parentheses")
`class Solution: def isValid(self, s: str) -> bool: stack = [] mapping = { ')': '(', '}': '{', ']': '[' }` ` for char in s: if char in mapping: top_element = stack.pop() if stack else '#'` ` if mapping[char] != top_element: return False else: stack.append(char)` ` return not stack`
![](https://static.platzi.com/media/user_upload/image-69a15b73-f4d7-41c6-872b-43cd7aa33c2c.jpg)
// versión de javascript function isValid(param) { const openChars = \['{', '\[', '('] const closeChars = \['}', ']', ')'] const arr = param.split('') let stackLength = 0 arr.forEach(e => { if(openChars.includes(e)){ stackLength ++ } if(closeChars.includes(e)){ stackLength -- } }) return stackLength === 0 } console.log( isValid("{{}}") )

Mi solucion en c++

#include <iostream>
#include <stack>
#include <string>

using namespace std;

bool esParentesisValido(string cadena)
{
    stack<char> pila;

    for (int i = 0; i < cadena.length(); i++)
    {
        if (cadena[i] == '(')
        {
            pila.push(cadena[i]);
        }
        else if (cadena[i] == ')')
        {
            if (pila.empty())
            {
                return false;
            }
            pila.pop();
        }
    }
    return true;
}

int main()
{
    string cadena = "())";
    if (esParentesisValido(cadena))
    {
        cout << "La cadena es valida" << endl;
    }
    else
    {
        cout << "La cadena no es valida" << endl;
    }
    return 0;
}

Comparto mi solución en python usando complejidad espacial O(1)
.
.
.
.
.
.
.
.

def isValid(s):
   num_open = 0
   for i in range(len(s)):
      if num_open <0:
         return False

      if s[i] == "(":
         num_open +=1
      elif s[i] == ")":
         num_open -= 1

   return num_open == 0