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


Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
    }
}