基础数据结构-栈

栈(stack):

头文件调用:#include<stack>

                                  

栈定义:stack<type> sta ;

栈操作:sta.empty() ;     检查栈是否为空,是则返回true,否返回false;

            sta.size() ;          返回栈中元素个数 ;

            sta.pop() ;          删除顶端 ;

            sta.top() ;           返回顶端值 ;

            sta.push() ;         向栈中压入值 ;


栈例题:

Parentheses Balance

 

题目略;大意为判断每个右括号最近是否有左括号与之对应。

wa点,当无输入为空的时候也是yes ;

大致方法:对输入的字符为左括号压入栈,为右括号则判栈的最上方是否为对应左括号,最后判断栈是否为空及是否每个左括号都已对应 ;

注意点,不能直接用字符串输入,中间可能有空格;

ac代码如下:

#include <iostream>
#include <cstdio>
#include <stack>
#include <string.h>
using namespace std ;

int main ()
{
    int t ;
    scanf("%d" , &t ) ;
    getchar() ;
    for( ; t!=0 ; t-- ) 
    {
    	stack <char> s ;
    	char str[1000] ;
    	int can = 1;
		gets( str ) ;
		if( str[0] == '\0' )
		{
			printf("Yes\n");
			continue ;
		}
    	for ( int i=0 ; i<strlen(str) ; i++ )
    	{
    		if( str[i] == '[' || str[i] == '(' )
    		{
    			s.push( str[i] ) ;
    			continue ;
			}
    		if( ( str[i] == ')' || str[i] == ']' ) && s.empty() )
    		{
    				can = 0 ;break ;
			}
			if( str[i] == ')' )
			{
				if( s.top() == '(' ) s.pop() ;
				else
				{
					can = 0 ;
				}
			}
			if( str[i] == ']' )
			{
				if( s.top() == '[' ) s.pop() ;
				else
				{
					can = 0 ;
				}
			}
    	}
    	if( !s.empty() ) 
    	can = 0 ;
		if( can == 1 ) printf("Yes\n") ;
		else printf("No\n") ;
	}
	return 0 ;
} 


总结分析:判断写的过于复杂,总点在于分析题目中是否运用栈;

                                                             

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值