Advertisement
Guest User

Untitled

a guest
Dec 21st, 2011
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.53 KB | None | 0 0
  1. public static class BracketsChecker {
  2.  
  3.     public class BracketMismatchException : ApplicationException {
  4.     }
  5.  
  6.     public class ExtraOpeningBracketException : ApplicationException {
  7.     }
  8.  
  9.     public class ExtraClosingBracketException : ApplicationException {
  10.     }
  11.  
  12.     private class Bracket {
  13.  
  14.         char[] openChars;
  15.  
  16.         char[] closeChars;
  17.  
  18.         public Bracket(char[] openChars, char[] closeChars) {
  19.             this.openChars = openChars;
  20.             this.closeChars = closeChars;
  21.         }
  22.  
  23.     }
  24.  
  25.     private static readonly Bracket[] Brackets = new[] {
  26.         new Bracket(new[] { '(' }, new[] { ')' }),
  27.         new Bracket(new[] { '[' }, new[] { ']' }),
  28.         new Bracket(new[] { '{' }, new[] { '}' }),
  29.     }
  30.  
  31.     private static readonly Dictionary<char, Bracket> BracketsByOpenChar = (from bracket in Brackets from openChar in bracket.openChars select new KeyValuePair<char, Bracket>(openChar, bracket)).ToDictionary();
  32.  
  33.     private static readonly HashSet<char> CloseChars = new HashSet<char>(from bracket in Brackets from closeChar in bracket.CloseChars select closeChar);
  34.  
  35.     public static void CheckString(string str) {
  36.         Stack<Bracket> currentState = new Stack<Bracket>();
  37.         for(int i=0; i<str.length; i++) {
  38.             if(BracketsByOpenChar.ContainsKey(str[i])) {
  39.                 currentState.Push(BracketsByOpenChar[str[i]]);
  40.             } else if(CloseChars.Contains(str[i])) {
  41.                 if(currentState.IsEmpty) {
  42.                     throw new ExtraClosingBracketException();
  43.                 }
  44.                 if(!currentState.Peek().closeChars.Contains(str[i])) {
  45.                     throw new BracketsMismatchException();
  46.                 }
  47.                 currentState.Pop();
  48.             }
  49.         }
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement