当前位置:   article > 正文

数据结构与算法——栈的应用括号匹配_数据结构括号匹配算法

数据结构括号匹配算法

  括号匹配问题是对于栈的应用,那么如何利用栈解决括号匹配的问题呢?

一、引入概念

一个表达式中利用圆括号或方括号及花括号来表示运算的优先级,将这些括号提取出来就构成了括号序列

例如:表达式[(a+b)*c]-[e-f] 其括号序列为[()][]

合法的括号序列称为匹配序列,不合法的括号序列称为不匹配序列

匹配序列示例: ([()]) [][]() ()[()]

不匹配序列示例:([()] ][]() (][()]

二、算法分析

1.计算机从左往右扫描表达式,扫描至左括号时,将该左括号压入栈中。

2.直至遇见右括号,将栈中栈底的括号与该右括号进行比较,若结果为匹配,则继续进行扫描。若结果为不匹配,则该序列不合法。

3.若全部元素遍历完毕,栈中无剩余元素,则该序列合法;栈中仍然存在元素,则该序列不合法。

三、过程分析

1.初始化空栈,判断1[为左括号,将1入栈

2.判断2(,2仍为左括号,将2入栈

3.判断3),3为右括号,与栈顶元素(匹配,匹配成功,2出栈

4.判断4],4为右括号,与栈顶元素1[进行匹配,匹配成功,1出栈

5.判断5[,5为左括号,将5入栈

6.判断6],6为右括号,与栈顶元素匹配,匹配成功,5出栈

7.序列遍历完毕,且栈中无元素,判断该序列为合法序列

(该案例及图片来自于知乎“半颗糖逗”)

四、代码如下

  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #define STACK_MAX_SIZE 10
  4. /**
  5. * Linear stack of integers. The key is data.
  6. */
  7. typedef struct CharStack {
  8. int top;
  9. int data[STACK_MAX_SIZE]; //The maximum length is fixed.
  10. } *CharStackPtr;
  11. /**
  12. * Output the stack.
  13. */
  14. void outputStack(CharStackPtr paraStack) {
  15. for (int i = 0; i <= paraStack->top; i ++) {
  16. printf("%c ", paraStack->data[i]);
  17. }// Of for i
  18. printf("\r\n");
  19. }// Of outputStack
  20. /**
  21. * Initialize an empty char stack. No error checking for this function.
  22. * @param paraStackPtr The pointer to the stack. It must be a pointer to change the stack.
  23. * @param paraValues An int array storing all elements.
  24. */
  25. CharStackPtr charStackInit() {
  26. CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(struct CharStack));
  27. resultPtr->top = -1;
  28. return resultPtr;
  29. }//Of charStackInit
  30. /**
  31. * Push an element to the stack.
  32. * @param paraValue The value to be pushed.
  33. */
  34. void push(CharStackPtr paraStackPtr, int paraValue) {
  35. // Step 1. Space check.
  36. if (paraStackPtr->top >= STACK_MAX_SIZE - 1) {
  37. printf("Cannot push element: stack full.\r\n");
  38. return;
  39. }//Of if
  40. // Step 2. Update the top.
  41. paraStackPtr->top ++;
  42. // Step 3. Push element.
  43. paraStackPtr->data[paraStackPtr->top] = paraValue;
  44. }// Of push
  45. /**
  46. * Pop an element from the stack.
  47. * @return The popped value.
  48. */
  49. char pop(CharStackPtr paraStackPtr) {
  50. // Step 1. Space check.
  51. if (paraStackPtr->top < 0) {
  52. printf("Cannot pop element: stack empty.\r\n");
  53. return '\0';
  54. }//Of if
  55. // Step 2. Update the top.
  56. paraStackPtr->top --;
  57. // Step 3. Push element.
  58. return paraStackPtr->data[paraStackPtr->top + 1];
  59. }// Of pop
  60. /**
  61. * Test the push function.
  62. */
  63. void pushPopTest() {
  64. printf("---- pushPopTest begins. ----\r\n");
  65. char ch;
  66. // Initialize.
  67. CharStackPtr tempStack = charStackInit();
  68. printf("After initialization, the stack is: ");
  69. outputStack(tempStack);
  70. // Pop.
  71. for (ch = 'a'; ch < 'm'; ch ++) {
  72. printf("Pushing %c.\r\n", ch);
  73. push(tempStack, ch);
  74. outputStack(tempStack);
  75. }//Of for i
  76. // Pop.
  77. for (int i = 0; i < 3; i ++) {
  78. ch = pop(tempStack);
  79. printf("Pop %c.\r\n", ch);
  80. outputStack(tempStack);
  81. }//Of for i
  82. printf("---- pushPopTest ends. ----\r\n");
  83. }// Of pushPopTest
  84. /**
  85. * Is the bracket matching?
  86. *
  87. * @param paraString The given expression.
  88. * @return Match or not.
  89. */
  90. bool bracketMatching(char* paraString, int paraLength) {
  91. // Step 1. Initialize the stack through pushing a '#' at the bottom.
  92. CharStackPtr tempStack = charStackInit();
  93. push(tempStack, '#');
  94. char tempChar, tempPopedChar;
  95. // Step 2. Process the string.
  96. for (int i = 0; i < paraLength; i++) {
  97. tempChar = paraString[i];
  98. switch (tempChar) {
  99. case '(':
  100. case '[':
  101. case '{':
  102. push(tempStack, tempChar);
  103. break;
  104. case ')':
  105. tempPopedChar = pop(tempStack);
  106. if (tempPopedChar != '(') {
  107. return false;
  108. } // Of if
  109. break;
  110. case ']':
  111. tempPopedChar = pop(tempStack);
  112. if (tempPopedChar != '[') {
  113. return false;
  114. } // Of if
  115. break;
  116. case '}':
  117. tempPopedChar = pop(tempStack);
  118. if (tempPopedChar != '{') {
  119. return false;
  120. } // Of if
  121. break;
  122. default:
  123. // Do nothing.
  124. break;
  125. }// Of switch
  126. } // Of for i
  127. tempPopedChar = pop(tempStack);
  128. if (tempPopedChar != '#') {
  129. return true;
  130. } // Of if
  131. return true;
  132. }// Of bracketMatching
  133. /**
  134. * Unit test.
  135. */
  136. void bracketMatchingTest() {
  137. char* tempExpression = "[2 + (1 - 3)] * 4";
  138. bool tempMatch = bracketMatching(tempExpression, 17);
  139. printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
  140. tempExpression = "( ) )";
  141. tempMatch = bracketMatching(tempExpression, 6);
  142. printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
  143. tempExpression = "()()(())";
  144. tempMatch = bracketMatching(tempExpression, 8);
  145. printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
  146. tempExpression = "({}[])";
  147. tempMatch = bracketMatching(tempExpression, 6);
  148. printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
  149. tempExpression = ")(";
  150. tempMatch = bracketMatching(tempExpression, 2);
  151. printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
  152. }// Of bracketMatchingTest
  153. /**
  154. The entrance.
  155. */
  156. void main() {
  157. // pushPopTest();
  158. bracketMatchingTest();
  159. }// Of main

(该代码誊抄自于闵帆老师)

五、运行结果

  1. Is the expression '[2 + (1 - 3)] * 4' bracket matching? 1
  2. Is the expression '( ) )' bracket matching? 0
  3. Is the expression '()()(())' bracket matching? 1
  4. Is the expression '({}[])' bracket matching? 1
  5. Is the expression ')(' bracket matching? 0
  6. Press any key to continue

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/880374
推荐阅读
相关标签
  

闽ICP备14008679号