En este post te voy a explicar como resolví el problema: Valid Parenthesis de la plataforma Leetcode.
Primeros pasos.
Este ejercicio: Valid Parenthesis, es sencillo, necesitas recorrer la cadena de derecha a izquierda. Los elementos que no sean paréntesis abiertos y cerrados: (), [], {} se agregan a la pila. Cuando tienes un paréntesis abierto y cerrado del mismo tipo, eliminas el último valor de la pila. Si quedan más de un elemento en la pila, la cadena no es válida.
Solución.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
public class Solution { | |
enum Action | |
{ | |
AddToStack, | |
RemoveFromStack, | |
} | |
public static bool IsValid(string parenthesis) | |
{ | |
var stack = new Stack<string>(); | |
for (var i = parenthesis.Length - 1; i >= 0; i--) | |
{ | |
var rightValue = parenthesis[i].ToString(); | |
var leftValue = GetLefValue(); | |
var action = GetAction(leftValue, rightValue); | |
ApplyAction(action, rightValue); | |
} | |
return stack.Count == 0; | |
Action GetAction(string left, string right) | |
{ | |
return (left, right) switch | |
{ | |
(")", "(") => Action.RemoveFromStack, | |
("}", "{") => Action.RemoveFromStack, | |
("]", "[") => Action.RemoveFromStack, | |
_ => Action.AddToStack | |
}; | |
} | |
string GetLefValue() => stack.Any() ? stack.Peek() : string.Empty; | |
void ApplyAction(Action action, string rightValue) | |
{ | |
switch (action) | |
{ | |
case Action.AddToStack: | |
stack.Push(rightValue); | |
break; | |
case Action.RemoveFromStack: | |
_ = stack.Pop(); | |
break; | |
} | |
} | |
} | |
public static void Main(string[] args) | |
{ | |
Console.WriteLine(IsValid("((){}())")); | |
} | |
} |
Últimas entradas de Gustavo Sánchez (ver todo)
- NVL in SQL Server - 2023-11-01
- ¿Que es Cake Build? - 2023-02-22
- #How to fix error: MSB4019: The imported project «Microsoft.Data.Tools.Schema.SqlTasks.targets» was not found - 2023-02-20