zoukankan      html  css  js  c++  java
  • 堆栈小应用:配对

        在“配对”问题中,栈将使问题大大简化和更富逻辑性。一个简单的例子,我们来看看如何判断表达式中的小括号是否配对。如果没有栈,这问题就不会那么美妙了。
        只要你脑袋里能联想到“栈”这个词,解决方案就会变得非常简单。

        遍历表达式,遇到左括号则进栈,遇到有括号则将栈顶左括号弹出,遍历完后,栈应该为空。如果不能顺利执行此过程那么表达式的括号则一定不匹配。

      
    #include<iostream>
    #include
    <string>
    #include
    <stack>

    using namespace std;

    int main()
    {
        stack
    <char> stk;
        
    string exp;
        
    bool ok = true;

        cin
    >>exp;

        
    const int len = exp.length();
        
    for(int i=0; i<len; i++)
        
    {
            
    if(exp[i] == '(')
            
    {
                stk.push(exp[i]);
            }
    else if(exp[i] == ')')
            
    {
                
    if(!stk.empty())
                
    {
                    stk.pop();
                }

                
    else
                
    {
                    cout
    <<"not find \'(\' for \')\' at index of "<<i<<endl;
                    ok 
    = false;
                }

            }

        }


        
    if(!stk.empty())
        
    {
            cout
    <<"not find \')\' for \'(\'"<<endl;
            ok 
    = false;
        }


        
    if(ok)
        
    {
            cout
    <<"ok"<<endl;
        }


        
    return 0;
    }




  • 相关阅读:
    sql STUFF用法
    关于原型链
    原生js事件绑定
    http常见7种请求
    关于linux的一些常用的指令
    flex布局详解
    html5 新增元素以及css3新特性
    css浮动以及清除
    css 浮动
    计算机网络
  • 原文地址:https://www.cnblogs.com/zhouyinhui/p/395117.html
Copyright © 2011-2022 走看看