LeetCode刷题——括号匹配问题

x33g5p2x  于2021-10-25 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(397)

前言:这次介绍一道用C语言刷题很难受的一题,主要用到“栈”的思想。

1.括号匹配问题

OJ链接

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

思路分析:

由于栈结构的特殊性,非常适合做对称匹配类的题目。

首先要弄清楚,字符串里的括号不匹配有几种情况。

先来分析一下 这里有三种不匹配的情况:


  1. 第一种情况,字符串里左方向的括号多余了 ,所以不匹配。

  2. 第二种情况,括号没有多余,但是 括号的类型没有匹配上。

  3. 第三种情况,字符串里右方向的括号多余了,所以不匹配。

我们的代码只要覆盖了这三种不匹配的情况,就不会出问题。

题解:

借助上次博客实现的栈实现此题。在栈中存放左括号,遇到右括号,则出栈顶元素,判断栈顶元素是否和当前括号匹配,如果不匹配,则说明不匹配。遍历完所有字符,如果栈为空,则表示完全匹配。

  1. //上次博客中栈的定义
  2. typedef char STDatatype;
  3. typedef struct Stack
  4. {
  5. STDatatype* a;
  6. int top; // 栈顶
  7. int capacity;
  8. }ST;
  9. void StackInit(ST* ps);
  10. void StackDestroy(ST* ps);
  11. void StackPush(ST* ps, STDatatype x);
  12. void StackPop(ST* ps);
  13. bool StackEmpty(ST* ps);
  14. int StackSize(ST* ps);
  15. STDatatype StackTop(ST* ps);
  16. void StackInit(ST* ps)
  17. {
  18. assert(ps);
  19. ps->a = NULL;
  20. ps->top = 0; // -1
  21. ps->capacity = 0;
  22. }
  23. void StackDestroy(ST* ps)
  24. {
  25. assert(ps);
  26. if (ps->a)
  27. {
  28. free(ps->a);
  29. }
  30. ps->a = NULL;
  31. ps->top = 0;
  32. ps->capacity = 0;
  33. }
  34. void StackPush(ST* ps, STDatatype x)
  35. {
  36. assert(ps);
  37. // 检查空间够不够,不够就增容
  38. if (ps->top == ps->capacity)
  39. {
  40. int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
  41. STDatatype* tmp = realloc(ps->a, sizeof(STDatatype)*newcapacity);
  42. if (tmp == NULL)
  43. {
  44. printf("rellaoc fail\n");
  45. exit(-1);
  46. }
  47. ps->a = tmp;
  48. ps->capacity = newcapacity;
  49. }
  50. ps->a[ps->top] = x;
  51. ps->top++;
  52. }
  53. void StackPop(ST* ps)
  54. {
  55. assert(ps);
  56. assert(!StackEmpty(ps));
  57. --ps->top;
  58. }
  59. bool StackEmpty(ST* ps)
  60. {
  61. assert(ps);
  62. return ps->top == 0;
  63. }
  64. int StackSize(ST* ps)
  65. {
  66. assert(ps);
  67. return ps->top;
  68. }
  69. STDatatype StackTop(ST* ps)
  70. {
  71. assert(ps);
  72. assert(!StackEmpty(ps));
  73. return ps->a[ps->top - 1];
  74. }
  75. //正文开始
  76. bool isValid(char * s){
  77. ST st;
  78. StackInit(&st);
  79. bool match=true;
  80. while(*s)
  81. {
  82. if(*s=='('||*s=='{'||*s=='[')
  83. {
  84. StackPush(&st,*s);
  85. ++s;
  86. }
  87. else
  88. {
  89. if(StackEmpty(&st))
  90. {
  91. match = false;
  92. break;
  93. }
  94. char ch = StackTop(&st);
  95. StackPop(&st);
  96. if((*s == ']' && ch != '[')
  97. || (*s == '}' && ch != '{')
  98. || (*s == ')' && ch != '('))
  99. {
  100. match = false;
  101. break;
  102. }
  103. else
  104. {
  105. ++s;
  106. }
  107. }
  108. }
  109. if(match == true)
  110. {
  111. match = StackEmpty(&st);
  112. }
  113. StackDestroy(&st);
  114. return match;
  115. }

嗯,你没有看错,这道题用C语言实现需要手动写一个栈,正文部分其实很少,等后边C++学到STL标准库可以省力很多!

相关文章