Ieee全球极限编程大赛往届题目“Look and Say”题解/字符串操作/递归

题目

You should implement a function that finds the N-th element in the Look-and-say sequence:

  • 1,11,21,1211,111221,312211,13112221,11132132111,11,21,1211,111221,312211,13112221,1113213211

To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. For example:

  • 11 is read off as "one 11" or 1111.
  • 1111 is read off as "two 11s" or 2121.
  • 2121 is read off as "one 22, then one 11" or 12111211.
  • 12111211 is read off as "one 11, one 22, then two 11s" or 111221111221.
  • 111221111221 is read off as "three 11s, two 22s, then one 11" or 312211312211.

Standard input

The template code reads on the first line a single integer NN.

Standard output

The template calls your functions and prints the returned result.

 

InputOutput
5
111221
10
13211311123113112211

 

题目分析

该Look-and-say序列从“1”开始,1可以读作“一个一”所以序列的下一个数据为“11”,11可以读作“两个一”所以序列的下一个数据为“21”(2表示个数,1表示数),以此类推......

要求输入一个整数N,输出序列里的第N个数据,例如:输入5,输出111221(序列里的第五个数)

那怎么解决这类问题呢?其实对于这个Look-and-say序列的规律是很明显的了,但是关键在于我们怎么用代码表示出这个规律,表示出来之后怎么满足输入输出的要求?这里很明显用递归是非常简单的,我们要找第N个数据,那么只需要找到它的前一个数据然后进行按规律变化就可以了,所以编写一个lookAndSay(int n)函数在里面递归lookAndSay(n-1)就可以了,最后返回得出的结果,这里建议用string类型比较简单

代码

#include<bits/stdc++.h>
using namespace std;

string lookAndSay(int n){
    string s;
    if(n==1){
        return "1";
    }
    else{
        s = lookAndSay(n-1);
        string ans = "";
        int count = 1;
        for(int i=1;i<s.length();i++){
            if(s[i]==s[i-1]){
                count++;
            }
            else{
                ans += to_string(count);
                ans += s[i-1];
                count = 1;
            }
        }
        ans += to_string(count);
        ans += s[s.length()-1];
        return ans;
    }

}
int main(){
    int n;
    cout<<"Enter the number of terms: ";
    cin>>n;
    cout<<lookAndSay(n);
    return 0;
}

交流讨论

以上均为个人拙见,若有错误或者改进之处,欢迎评论区留言交流讨论

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SR_world

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值