For the students of computer science, they will be familiar with a word: program design = algorithm + data structure. According to the author's understanding, the so-called programming is actually to solve the actual problem of programming, the so-called algorithm is a solution to the problem of a certain way of thinking, but the thinking needs to get the programming practice, which needs to be based on data structure. A good data structure can enable us to process the information faster and more efficiently, some of the problems of simulation, mathematics background is not deep, just based on efficient data structure can be solved. So this chapter, we will separate the queue, stack, double-ended queue out, combined with specific topics to see how they are flexible to use in the problem-solving strategy.
Considering the author's introduction to several simple linear structures in "Getting Started classic" and "Aha algorithm", the concept and the use of STL are not discussed here. Mainly through specific topics to improve the ability to use.
Do not match the parentheses problem:
Parentheses: ().
Brackets: []
Curly braces: {}
Now give a string consisting of three types of parentheses, and programmatically determine if the three types of parentheses match. Example Input value: 3 () () ({[}]) ({}[() {}]) example output value: Yes NO Yes Analysis: If you do a simulation, the process becomes cumbersome and very poorly designed. But if we are based on the data structure of the stack, we will find that it makes the problem extremely simple. Because the law of the parentheses matching is exactly the same as the "in and first out" feature of the stack. We just need to put all the left parenthesis sequentially into the stack, once we encounter the closing parenthesis, we will match the top element of the stack, if matching, stack top element out of the stack, otherwise, complete the judgment.
The simple reference code is as follows.
BOOLWellmatched (Const string&formula) { Const stringOpening"({["), closing (")}]"); Stack<Char>OpenStack; for(inti =0; i < formula.size (); + +i) {if(Opening.find (formula[i])! =-1) Openstack.push (Formula[i]);//left parenthesis, press stack Else//closing parenthesis, matching { if(Openstack.empty ())return false;//when the stack is empty, the match fails if(Opening.find (Openstack.top ())! = Closing.find (Formula[i]))return false;//does not matchOpenstack.pop ();//pop-up stack top element } returnOpenstack.empty ();//traversal string all characters, if stack empty, match successfully }}
Algorithmic combat strategy-chaper19-queues, stacks, and double-ended queues