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

相关文章:

  • 2021-07-06
  • 2021-08-22
  • 2021-10-12
  • 2021-07-17
  • 2021-08-23
  • 2021-11-23
  • 2021-05-03
猜你喜欢
  • 2021-08-07
  • 2021-07-23
  • 2021-09-23
  • 2022-12-23
  • 2022-03-03
  • 2022-01-14
  • 2021-07-18
相关资源
相似解决方案