Le migliori 150 intervisteFacile

Parentesi valide

Guida dettagliata e implementazione Python per il problema delle "parentesi valide".

Dichiarazione del problema

Facile

Data una stringa s contenente solo i caratteri '(', ')', '{', '}', '[' e ']', determinare se la stringa di input è valida.

Una stringa di input è valida se:

1. Le parentesi aperte devono essere chiuse con parentesi dello stesso tipo.

2. Le parentesi aperte devono essere chiuse nell'ordine corretto.

3. Ad ogni parentesi chiusa corrisponde una parentesi aperta dello stesso tipo.

Scrivi una funzione isValid(s: str) -> bool.

Vincoli
  • 1 <= len(s) <= 10^4
  • s consists of parentheses only: '()[]{}'

Esempi

Example 1
Input
s = "()"
Output
True
Explanation

A single pair of matching parentheses is valid.

Example 2
Input
s = "()[]{}"
Output
True
Explanation

Three pairs of matching brackets, each closed in order.

Example 3
Input
s = "(]"
Output
False
Explanation

Opening '(' is closed by ']' which is the wrong type.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche dello stack come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Apri nell'editor
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.