首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++ Stack Application - (Parenthesis Matching) 堆栈运用之"括号匹配"

2013-03-22 
C++ Stack Application - (Parenthesis Matching) 堆栈应用之括号匹配In this problem we are to match

C++ Stack Application - (Parenthesis Matching) 堆栈应用之"括号匹配"

In this problem we are to match the left and right parentheses in a character string. For example, the string (a*(b+c)+d) has left parentheses at positions 0 and 3 and right parentheses at positions 7 and 10. The left parenthesis at position 0 matches the right at position 10, while the left parenthesis at position 3 matches the right parenthesis at position 7. In the string (a+b))(, the right parenthesis at position 5 has no matching left parenthesis, and the left parenthesis at position 6 has no matching right parenthesis. Our objective is to write a C++ program that outputs the pairs of matched parentheses as well as those parentheses for which there is no match.

We observe that if we scan the input string from left to right, then each right parenthesis is matched to the most recently seen unmatched left parenthesis. This observation motivates us to save the position of left parentheses on a stack as they are encountered in a left-to-right scan. When a right parenthesis is encountered, it is matched to the left parenthesis( if any) at the top of the stack. The matched left parenthesis is deleted from the stack.


http://www.waitingfy.com/?p=449

热点排行