[C++]利用栈实现字符串里的括号匹配

题目:Valid Parentheses

题目来源:leetcode

题目描述:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order

 解题思路:

  1. 建立一个string的栈
  2. 指针指向字符串(下标)
  3. 与栈顶的字符比较,若栈为空直接压入栈,如和栈顶匹配,则将栈顶弹出,若未匹配,括号直接压入栈中
  4. 指针向后移一位,回到3,直到字符串被扫描完
  5. 如栈为空,则括号匹配为真,反则为假

全部代码:

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         bool match(char,char);
 5         stack<char> stk;
 6         for(int i=0;i<s.size();++i)
 7         {
 8             if(stk.size()==0) stk.push(s[i]);
 9             else
10             {
11                 if(match(stk.top(),s[i])) stk.pop();
12                 else stk.push(s[i]);
13             }
14         }
15         if(stk.size()==0) return true;
16         else return false;
17     }
18 };
19 bool match(char f,char l)
20 {
21     switch(f)
22     {
23         case '(': if(l==')') return true;break;
24         case '[': if(l==']') return true;break;
25         case '{': if(l=='}') return true;break;
26      }
27     return false;
28 }

 

原文链接: https://www.cnblogs.com/cuphoria/p/9605774.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    [C++]利用栈实现字符串里的括号匹配

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/280880

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午5:13
下一篇 2023年2月15日 上午5:14

相关推荐