Bracket Matching Problem - Algorithm Topics

Algorithm Data Structure Interview Share Symbol Matching Questions

Today, I saw a classmate in the post asking, if a string contains curly brackets and parentheses, how can we solve the bracket matching problem. Let's take a look at this question today. Follow our previous routine, step by step:

Make sure we understand the problem and try an example to make sure we understand it correctly.

For example, such brackets are matched, (), {}, ({}), ({()}(){}), and similar to {(, {, ({) are not matched.

Think about what methods you can use to solve the problem, which one would you choose and why?

Let's take this string as an example, ({()}(){}), the last one) matches the first one (, the last one} matches the third last one. So we can scan from the end to the beginning, The first) we record first, the first } we record it, the third { we find it matches the }, eliminate it, the fourth is), we save, the fifth is (, we Find a match with the fourth one, eliminate it, and so on, to the last one (, we find that it is also the first match at the beginning. So we naturally think of the stack, if it does not match, we push it into the stack, and if it matches, we pop it out of the stack.

Explain your algorithm and how to implement it

We declare two stacks, first push all characters into the stack in turn, and then pop them out one by one. When popping the stack, we check whether the first character in the auxiliary stack matches, if it matches, we pop it out of the stack, otherwise push it into the stack. When all characters in the main stack are popped, we check if the auxiliary stack is empty. Empty means an exact match, otherwise no match.

When writing code, remember to explain what you are doing

Let's define a stack first. Generally, we will use an array. Here we simply use a list to deal with it, and implement its Pop, Push, and IsEmpty methods. Look at the code:

public class Mystack<T>  
   {  
       private List<T> list = new List<T>();  

       public Mystack()  
       { }  

       public Mystack(T[] input)  
       {  
           if (input != null)  
           {  
               for (int index = 0; index < input.Length; index++)  
               {  
                   list.Add(input[index]);  
               }  
           }  
       }  
       public T Pop()  
       {  
           if (!this.IsEmpty())  
           {  
               T element = list[list.Count-1];  

               list.RemoveAt(list.Count-1);  

               return element;  
           }  

           throw new IndexOutOfRangeException("The stack is empty already.");  

       }  

       public void Push(T element)  
       {  
           list.Add(element);  
       }  

       public bool IsEmpty()  
       {  
           return this.list.Count == 0;  
       }  
   }  

Next, we look at the algorithm:


public static bool IsMatch(string input)  
      {  
          if (!string.IsNullOrEmpty(input))  
          {  
              Mystack<char> stack = new Mystack<char>(input.ToArray());  

              Mystack<char> secondStack = new Mystack<char>();  

              while (!stack.IsEmpty())  
              {  
                  char current = stack.Pop();  

                  if (secondStack.IsEmpty())  
                  {  
                      secondStack.Push(current);  
                  }  
                  else  
                  {  
                      char target = secondStack.Pop();  

                      if (!IsClosed(current, target))  
                      {  
                          secondStack.Push(target);  
                          secondStack.Push(current);  
                      }  
                  }  
              }  

              return secondStack.IsEmpty();  
          }  

          return false;  
      }  

This uses an IsClosed method, which we use to match ( and ), { and }, see the code:


private static bool IsClosed(char first, char second)  
 {  
     if (first == '(') return second == ')';  

     if (first == '{') return second == '}';  

     return false;  
 }    

Finally, let's test this method together:

static void Main(string[] args)  
{  
    string input = "({(){}})";  

    var result = IsMatch(input);  

    Console.WriteLine(result);  
}  

Welcome everyone to pay attention to my official account, as well as my series of video tutorials , data structures and algorithms and classic algorithm interview questions , sorting topics , and linked lists .

If you have a better solution, please discuss.

No public

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325344444&siteId=291194637