Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class BracketsChecker {
- public class BracketMismatchException : ApplicationException {
- }
- public class ExtraOpeningBracketException : ApplicationException {
- }
- public class ExtraClosingBracketException : ApplicationException {
- }
- private class Bracket {
- char[] openChars;
- char[] closeChars;
- public Bracket(char[] openChars, char[] closeChars) {
- this.openChars = openChars;
- this.closeChars = closeChars;
- }
- }
- private static readonly Bracket[] Brackets = new[] {
- new Bracket(new[] { '(' }, new[] { ')' }),
- new Bracket(new[] { '[' }, new[] { ']' }),
- new Bracket(new[] { '{' }, new[] { '}' }),
- }
- private static readonly Dictionary<char, Bracket> BracketsByOpenChar = (from bracket in Brackets from openChar in bracket.openChars select new KeyValuePair<char, Bracket>(openChar, bracket)).ToDictionary();
- private static readonly HashSet<char> CloseChars = new HashSet<char>(from bracket in Brackets from closeChar in bracket.CloseChars select closeChar);
- public static void CheckString(string str) {
- Stack<Bracket> currentState = new Stack<Bracket>();
- for(int i=0; i<str.length; i++) {
- if(BracketsByOpenChar.ContainsKey(str[i])) {
- currentState.Push(BracketsByOpenChar[str[i]]);
- } else if(CloseChars.Contains(str[i])) {
- if(currentState.IsEmpty) {
- throw new ExtraClosingBracketException();
- }
- if(!currentState.Peek().closeChars.Contains(str[i])) {
- throw new BracketsMismatchException();
- }
- currentState.Pop();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement