| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.ValidParentheses; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ValidParenthesesStackDictionary : IValidParentheses |
| | 16 | | { |
| 5 | 17 | | private readonly Dictionary<char, char> _parenthesesDictionary = new() { { ')', '(' }, { '}', '{' }, { ']', '[' } }; |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="s"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public bool IsValid(string s) |
| 5 | 26 | | { |
| 5 | 27 | | var parenthesesStack = new Stack<char>(); |
| | 28 | |
|
| 58 | 29 | | foreach (var c in s) |
| 22 | 30 | | { |
| 22 | 31 | | if (_parenthesesDictionary.TryGetValue(c, out var value)) |
| 11 | 32 | | { |
| 11 | 33 | | if (parenthesesStack.Count == 0 || parenthesesStack.Pop() != value) |
| 1 | 34 | | { |
| 1 | 35 | | return false; |
| | 36 | | } |
| 10 | 37 | | } |
| | 38 | | else |
| 11 | 39 | | { |
| 11 | 40 | | parenthesesStack.Push(c); |
| 11 | 41 | | } |
| 21 | 42 | | } |
| | 43 | |
|
| 4 | 44 | | return parenthesesStack.Count == 0; |
| 5 | 45 | | } |
| | 46 | | } |