烟大 2241: 相同序列(栈和队列)

2241: 相同序列(栈和队列)

Time Limit: 1 Sec  Memory Limit: 1000 MB
Submit: 2  Solved: 2
[Submit][Status][Web Board]

Description

   试写一个算法,识别依次读入的一个以@为结束符的字符序列是否为形如‘序列1&序列2’模式的字符序列。其中序列1和序列2中都不含字符‘&’,且序列2是序列1的逆序列。输出YES或者NO。

Input

a+b&b+a

Output

YES

Sample Input

1+3&3-1

Sample Output

NO

HINT

Source 


Code:

 1 //将&前的字符串依次压入栈中,再拿出来依次和&后的字符串比较
 2 
 3 #include <iostream>
 4 #include <cstring>
 5 #include <stack>
 6 using namespace std;
 7 int main()
 8 {
 9     string l;
10     while(cin>>l){
11         int i,j;
12         stack <char> s;
13         for(i=0;i<l.length();i++){
14             if(l[i]=='&')
15                 break;
16             else
17                 s.push(l[i]);
18         }
19         for(j=i+1;j<l.length();j++){
20             if(s.top()==l[j])
21                 s.pop();
22             else
23                 break;
24         }
25         if(!s.empty())    //栈不是空的
26             cout<<"NO"<<endl;
27         else{
28             if(j==l.length())
29                 cout<<"YES"<<endl;
30             else
31                 cout<<"NO"<<endl;
32         }
33     }
34     return 0;
35 }
View Code

Freecode : www.cnblogs.com/yym2013

原文地址:https://www.cnblogs.com/yym2013/p/3255203.html