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);
}
}
}

1038

被折叠的 条评论
为什么被折叠?



