晴神PAT 1140 Look-and-say Sequence (20 分)

15 篇文章 0 订阅

Look-and-say sequence is a sequence of integers as the following:

D, D1, D111, D113, D11231, D112213111, ...

Sample Input:

1 8

Sample Output:

1123123111

我的代码:

#include<iostream>
#include<string>
#include<sstream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<map>
#include<queue>
#include<unordered_map>
using namespace std;

//15:21

int main()
{
	freopen("C:\\Users\\chenzhuo\\Desktop\\in.txt", "r", stdin);
	string tmp = "";
	char c; cin >> c; tmp =tmp+ c;
	int n; cin >> n;
	for (int i = 1; i < n; i++)
	{
		//cout << 1;
		string tmp1="";
		char last = tmp[0];
		//cout << last;
		int sz = 0;
		for (int j = 0; j < tmp.size(); j++)
		{
			if (tmp[j] == last)
			{
				sz++;
			}
			else
			{
				tmp1 += last;
				last = tmp[j];
				char cc = '0'; cc += sz;
				tmp1 =tmp1+ cc;
				sz = 1;
			}
		}
		tmp1 += last;
		char cc = '0'; cc += sz; tmp1 = tmp1 + cc;
		tmp = tmp1;
		cout << tmp<<endl;
	}
	cout << tmp;
}


 

 

 

晴神代码优点:

循环不换行,显得紧密。

使用了函数 to_string 

两个for循环一次遍历。

#include <iostream>
using namespace std;
int main() {
    string s;
    int n, j;
    cin >> s >> n;
    for (int cnt = 1; cnt < n; cnt++) {
        string t;
        for (int i = 0; i < s.length(); i = j) {
            for (j = i; j < s.length() && s[j] == s[i]; j++);
            t += to_string((s[i] - '0') * 10 + j - i);
        }
        s = t;
    }
    cout << s;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值