Last active
February 26, 2020 02:32
-
-
Save aaronmbos/241416d5379e1e50d9cd449c982f77a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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