• [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 }
    原创供学习参考使用,转载请注明出处http://www.cnblogs.com/cuphoria/ @jm_epiphany
  • 相关阅读:
    Maven的生命周期
    Spring Framework: @RestController vs @Controller
    HTMl5的sessionStorage和localStorage
    Gradle下载类库源码
    Spring Boot, Java Config
    NodeJS简记
    8 commands to check cpu information on Linux
    守护进程之守护进程的惯例
    守护进程之单实例守护进程
    守护进程之出错记录
  • 原文地址:https://www.cnblogs.com/cuphoria/p/9605774.html
Copyright © 2020-2023  润新知