1140 Look-and-say Sequence

本文介绍了一种使用C++实现的字符串迭代生成算法,通过输入初始字符串和迭代次数,程序能够生成经过特定规则转换后的字符串。该算法涉及字符串操作、循环和条件判断等基本编程概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){
    vector<string> a;
    string d;
    int n;
    cin>>d>>n;
    string t;
    a.push_back(d);
    for(int i=1;i<n;i++){
        int cnt=1;
        t=a[i-1];
        string temp;
        for(int i=0;i<t.length();i++){
        	if(t[i]==t[i+1]){
        		cnt++;
			}else{
				temp+=to_string((t[i]-'0')*10+cnt);
				cnt=1;
			}
		}
		a.push_back(temp);
    }
    cout<<a[n-1]<<endl;
    return 0;
}

二刷更新一个方法~

#include<bits/stdc++.h> 
using namespace std;
int main()
{
	string s="";
	int d,n;
	cin>>d>>n;
	s=to_string(d);
	while(n-1>0){
		n--;
		string t="";
		int cnt=0;
		for(int i=0;i<s.length();i++){
			if(cnt==0){
				t+=s[i];cnt++;
			}else if(s[i]==t[t.length()-1]){
				cnt++;
			}else{
				t+=to_string(cnt);
				t+=s[i];cnt=0;cnt++;
			}
			if(i==s.length()-1) t+=to_string(cnt);
		}
		s=t;
		//cout<<s<<endl;
	}
	cout<<s;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值