Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution
- {
- private static readonly Dictionary<char, char> pairs = new Dictionary<char, char>
- {
- { '{', '}' },
- { '[', ']' },
- { '(', ')' }
- };
- private static char getMatchingClosingBracket(char bracket)
- {
- return pairs.First(s => s.Key == bracket).Value;
- }
- private static bool isOpeningBracket(char bracket)
- {
- return pairs.ContainsKey(bracket);
- }
- private static bool isBracket(char input)
- {
- return (pairs.ContainsKey(input) || pairs.ContainsValue(input));
- }
- private static bool isBalanced(string inputString)
- {
- #region Not used in turned in solution
- // NOT COMMITTED: before everything check if input is proper meaning if we have odd number of elements, answer is "NO" always
- // I could not commit this, because they added random "chars" in their examples so I had sometimes odd array sizes e.g. "[ab]c{(d5) (11)}" or "a[b]c)d"
- // before everything check if input is proper, meaning if we have odd number of elements, answer is always "false"
- //if (inputString.Length % 2 != 0)
- // return false;
- #endregion
- // Using stack as opposed to list because "pop" function, list doesn't have "POP" function as seen here: https://stackoverflow.com/a/24855955
- // (could implement my own, but I don't know how will this in-browser compiler react to it)
- Stack<char> containList = new Stack<char>();
- // Loop trough array
- for (int i = 0; i < inputString.Length; i++)
- {
- // Check if this is opening bracket
- if (isOpeningBracket(inputString[i]))
- {
- // If it is, push it in our stack
- containList.Push(inputString[i]);
- }
- else // If not
- {
- // Check if given string is a bracket at all
- if (!isBracket(inputString[i]))
- {
- // If it isn't just continue
- continue;
- }
- // If there are only closing brackets in string
- if (containList.Count == 0 && inputString.Length - 1 == i)
- return false;
- // If there is nothing in our stack, continue spinning
- if (containList.Count == 0)
- continue;
- // Check if we have closing bracket for this input
- if (getMatchingClosingBracket(containList.First()) == (inputString[i]))
- {
- // Once we find our closing bracket, pop it from stack (Note: Stack is FIFO)
- containList.Pop();
- }
- else
- {
- // Return result immediately, because something went horribly wrong :O
- return false;
- }
- }
- }
- return containList.Count <= 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment