Bracket matching problem-algorithm topic

Source: Internet
Author: User

Algorithm data structure interview sharing symbol matching problem

Today, I saw a classmate in the post asking, if a string contains curly braces and parentheses, how do we solve the parentheses matching problem. Let's look at this problem together today. According to our previous routines, step by step:

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

For example, such parentheses are matched, (), {}, ({}), ({()} () {}), and similar to {(, {, {) are mismatched.

Think about what you can do to solve the problem, which one will you choose, and why?

Let's take this string as an example, ({()} () {}), the last one matches the first (and the penultimate one} matches the third one.) So we can scan from tail to head, first we record, first we record, third {we find it and} are matched, eliminate, fourth is), we save, fifth is (we find and fourth match, eliminate, and so on, to the last (, We found that it was also the first match to begin with. So we naturally think of the stack, do not match us into the stack, match us on the stack.

Explain your algorithm and how to implement it

We declare two stacks, first of all the characters sequentially into the stack, and then one by one, out of the stack, we look at the auxiliary stack of the first character is matched, if we match out the stack, otherwise into the stack. When all the characters in the main stack are out of stack, we check if the secondary stack is empty. Null indicates an exact match, otherwise it does not match.

When writing code, remember, be sure to explain what you're doing.

We first define a stack, generally we will rely on the array, here we have a simple list to deal with, to achieve its pop, Push, IsEmpty method, see 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 a isclosed method that we use to match (and), {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);  }  

You are welcome to pay attention to my public number, as well as my series of video tutorials , data structures and algorithms and classical algorithms to guide questions, sorting lectures, List of topics .

Everyone has a better solution, also welcome to discuss Kazakhstan.

Bracket matching problem-algorithm topic

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.