How to check parentheses validation [duplicate]

  • A+
Category:Languages

This question already has an answer here:

I want to be able to get string and check if the Parentheses are valid.

For example:

"(ew)[]" - this will be valid.  "(ew[)]" - this will be not valid. 

This is what I have tried:

public static bool CheckString(string input) {     int braceSum = 0, squareSum = 0, parenSum = 0;      foreach (char c in input)     {           if (c == '{')             braceSum++;         if (c == '}')             braceSum--;         if (c == '[')             squareSum++;         if (c == ']')             squareSum--;         if (c == '(')             parenSum++;         if (c == ')')             parenSum--;          //check for negatives (pair closes before it opens)         if (braceSum < 0 || squareSum < 0 || parenSum < 0)             return false;     }      return (braceSum == 0 && squareSum == 0 && parenSum == 0); } 

So in both cases my code will return true. Do you have any suggestions about what I need to add in order for the program to work correctly?

 


Try classic Stack-based validation:

public static bool CheckString(string input) {   if (string.IsNullOrEmpty(input))     return true;    Stack<char> brackets = new Stack<char>();    foreach (var c in input) {     if (c == '[' || c == '{' || c == '(')       brackets.Push(c);     else if (c == ']' || c == '}' || c == ')') {       // Too many closing brackets, e.g. (123))       if (brackets.Count <= 0)         return false;        char open = brackets.Pop();        // Inconsistent brackets, e.g. (123]       if (c == '}' && open != '{' ||           c == ')' && open != '(' ||           c == ']' && open != '[')         return false;     }   }    // Too many opening brackets, e.g. ((123)    if (brackets.Count > 0)     return false;    return true; } 

Demo:

 string[] tests = new string[] {     "123",     "(123)",     "(1(23)",     "(12)3)",     "(ew)[]",     "(ew[)]",     "[12(34]56)",   };    string report = string.Join(Environment.NewLine, tests     .Select(test => $"{test,-10} : {(CheckString(test) ? "Valid" : "Invalid")}"));    Console.Write(report); 

Outcome:

123        : Valid (123)      : Valid (1(23)     : Invalid (12)3)     : Invalid (ew)[]     : Valid (ew[)]     : Invalid [12(34]56) : Invalid 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: