"Valid Parentheses" Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string input = "()";

    void Start()
    {
        Debug.Log(IsValid(input));
    }

    public bool IsValid(string s)
    {
        var valid_pairs = new Dictionary<char, char> { { '(', ')' }, { '{', '}' }, { '[', ']' } };
        var openingBrackets = new Stack<char>();
        foreach (var _char in s)
        {
            if(valid_pairs.ContainsKey(_char))
            {
                openingBrackets.Push(_char);
            }
            else
            {
                if(openingBrackets.Count == 0 || _char != valid_pairs[openingBrackets.Peek()])
                    return false;
                openingBrackets.Pop();
            }
        }
        return openingBrackets.Count == 0;
    }
}