栈(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 ;
}
总结分析:判断写的过于复杂,总点在于分析题目中是否运用栈;