您的位置:首页 > 编程语言 > C语言/C++

PAT甲级 1140 Look-and-say Sequence (20分) 字符串处理/C++

2020-06-24 04:26 477 查看

1140 Look-and-say Sequence (20分)

字符串处理

题目大意:这题和LeetCode里面的38. Count and Say(可以看看LeetCode的各种题解)差不多。只不过say和count的位置相反。

#include<iostream>                  //输入输出流头文件
#include<stack>                     //栈
#include<string>                    //C++string类
using namespace std;                //标准命名空间
void lookandsay(int d,int n);
int main(){                         //主函数
#ifdef ONLINE_JUDGE                 //如果有oj系统(在线判定),则忽略文件读入,否则使用文件作为标准输入
#else
freopen("1.txt", "r", stdin);   //从1.txt输入数据
#endif
int d,n;
cin>>d>>n;
if(n==1)cout<<d<<endl;
else
lookandsay(d,n);
return 0;                       //返回0,如果不返回0,PAT会报错
}
void lookandsay(int d,int n){
stack<int> s;//其实不需要用栈,直接用string就可以
s.push(d);
for(int i=1;i<n;i++){
string s1;
int x=s.top();
int count=0;
while(!s.empty()){
if(s.top()==x){count++;s.pop();}
else {
s1+='0'+x;
x=s.top();
s1+='0'+count;
count=0;
}
}
s1+='0'+x;
s1+='0'+count;
if(i==n-1)cout<<s1<<endl;
for(int j=s1.size()-1;j>=0;j--){
int x=s1[j]-'0';
s.push(x);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: