Advertisement
ivandrofly

check balanced brackets / parentheses

Mar 4th, 2021
889
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.74 KB | None | 0 0
  1. using System;
  2.  
  3. public class Program
  4. {
  5.     public static void Main()
  6.     {
  7.         Console.WriteLine(HasBalancedBrackets("[[[[[[[[foobar]]]]]]]]").ToString());
  8.     }
  9.  
  10.     private static bool HasBalancedBrackets(string input)
  11.     {
  12.         int count = 0;
  13.         for (int i = input.Length - 1; i >= 0; i--)
  14.         {
  15.             char ch = input[i];
  16.             if (ch == ']')
  17.             {
  18.                 count++;
  19.             }
  20.             else if (ch == '[')
  21.             {
  22.                 count--;
  23.             }
  24.  
  25.             // even if you check to the end there won't be enough to balance
  26.             if (i - count < 0)
  27.             {
  28.                 Console.WriteLine("too much close");
  29.                 return false;
  30.             }
  31.         }
  32.  
  33.         if (count > 0)
  34.         {
  35.             Console.WriteLine("too much close");
  36.         }
  37.         else if (count < 0)
  38.         {
  39.             Console.WriteLine("too much open");
  40.         }
  41.  
  42.         return count == 0;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement