-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem6.cs
More file actions
43 lines (39 loc) · 1.14 KB
/
Problem6.cs
File metadata and controls
43 lines (39 loc) · 1.14 KB
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
34
35
36
37
38
39
40
41
42
43
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/valid-parentheses/">Valid Parentheses</see>.
/// </summary>
public static class Problem6
{
private static readonly IDictionary<char, char> Map = new Dictionary<char, char>
{
['('] = ')',
['{'] = '}',
['['] = ']',
};
/// <summary>
/// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="s">String to traverse.</param>
/// <returns>True, if the input string is valid.</returns>
public static bool IsValid(string s)
{
var stack = new Stack<char>(s.Length);
foreach (var character in s)
{
if (Map.ContainsKey(character))
{
stack.Push(character);
}
else
{
if (stack.Count == 0 || Map[stack.Pop()] != character)
{
return false;
}
}
}
return stack.Count == 0;
}
}