38. Count and Say

38. Count and Say
Difficulty: Easy

The count-and-say sequence is the sequence of integers beginning as
follows: 1, 11, 21, 1211, 111221, …

1 is read off as “one 1” or 11. 11 is read off as “two 1s” or 21. 21
is read off as “one 2, then one 1” or 1211. Given an integer n,
generate the nth sequence.

Note: The sequence of integers will be represented as a string.

序列1, 11, 21, 1211, 111221, 312211, …,给的整数n,返回序列的第n个字符串。
1 “one 1”—-11 “two 1” —-21 “one 2 one 1” —- 1211 …

class Solution {
public:
    string countAndSay(int n) {
    string str = "1";
    string nstr;
    if (n == 1)
    {
        return str;
    }
    int count;
    int k = 1;
    while (k < n)
    {
        count = 0;
        int sub = 0;
        int size = str.size();
        nstr = "";
        for (int i = 0; i < size; i++)
        {
            if (str[i] == str[sub])  //若是相同的字符,记录次数
            {
                count++;
            }
            else   //若与上一个字符不同
            {
                nstr += count + '0';  //数字+'0'得到对应的字符
                nstr += str[sub];
                sub = i;
                count = 1;  //count=1,因为当前字符已出现一次
            }

        }

        nstr += count + '0';  //最后一个字符
        nstr += str[size-1];

        k++;
        str = nstr;
    }
    return str;
    }
};

数字+’0’得到对应的字符。

1.string类库
string str;
str.size()获得字符串的大小。不以‘\0’为结束标志
赋值时不能逐个字符赋值,

str[num++]=count+'0';  str[num++]=str[sub];   //**是错误的**

2.C风格字符串
char *ch;
strlen(ch)获得字符串的大小。以‘\0’为结束标志
赋值时只能逐个字符赋值,

ch[i]='a';   //是正确的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值