Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check parentheses validation [duplicate]

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?

like image 249
danny kob Avatar asked Sep 14 '18 08:09

danny kob


People also ask

How do you find duplicate parentheses in an expression?

If the number of characters encountered between the opening and closing parenthesis pair, which is equal to the value of the counter, is less than 1, then a pair of duplicate parenthesis is found else there is no occurrence of redundant parenthesis pairs. For example, (((a+b))+c) has duplicate brackets around “a+b”.

How do you validate parentheses?

Push an opening parenthesis on top of the stack. In case of a closing bracket, check if the stack is empty. If not, pop in a closing parenthesis if the top of the stack contains the corresponding opening parenthesis. If the parentheses are valid,​ then the stack will be empty once the input string finishes.

How would you validate a string of parentheses is balanced?

One approach to check balanced parentheses is to use stack. Each time, when an open parentheses is encountered push it in the stack, and when closed parenthesis is encountered, match it with the top of stack and pop it. If stack is empty at the end, return Balanced otherwise, Unbalanced.

Which data structure is best to find if an expression has an duplicate parenthesis or not?

Approach 1. In this approach, we will use the stack data structure and iterate through every character in the expression of the character is not a closed parenthesis ( ( ) then, we push it to the top of the stack. Otherwise, if a closing parenthesis is found we pop the stack until a '(' is found.


1 Answers

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)",
    "[1+2(3+4)][5+6)",
  };

  string report = string.Join(Environment.NewLine, tests
    .Select(test => $"{test,-15} : {(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
[1+2(3+4)][5+6) : Invalid
like image 160
Dmitry Bychenko Avatar answered Sep 18 '22 23:09

Dmitry Bychenko