堆栈小应用:配对

来源:互联网 发布:ui和程序员漫画 编辑:程序博客网 时间:2024/04/30 14:35
    在“配对”问题中,栈将使问题大大简化和更富逻辑性。一个简单的例子,我们来看看如何判断表达式中的小括号是否配对。如果没有栈,这问题就不会那么美妙了。
    只要你脑袋里能联想到“栈”这个词,解决方案就会变得非常简单。

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

  
#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;
}




原创粉丝点击