Skip to content

Instantly share code, notes, and snippets.

@aaronmbos
Last active February 26, 2020 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronmbos/241416d5379e1e50d9cd449c982f77a0 to your computer and use it in GitHub Desktop.
Save aaronmbos/241416d5379e1e50d9cd449c982f77a0 to your computer and use it in GitHub Desktop.
public class Solution
{
public bool IsValid(string s)
{
if (s == null || s.Length % 2 != 0) { return false; }
if (s == string.Empty) { return true; }
var isOpenDict = new Dictionary<string, bool> { { "(", true }, { "{", true }, { "[", true }, { ")", false }, { "}", false }, { "]", false } };
var matches = new Dictionary<string, string> { { "(", ")" }, { "{", "}" }, { "[", "]" } };
var nested = new List<string>();
for (var i = 0; i < s.Length; i++)
{
if (isOpenDict[s[i].ToString()])
{
nested.Add(s[i].ToString());
}
else
{
if (nested.Count == 0) { return false; }
if (matches[nested[nested.Count - 1]] == s[i].ToString())
{
nested.RemoveAt(nested.Count - 1);
continue;
}
return false;
}
}
if (nested.Count > 0) { return false; }
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment