Count and Say

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.

此题看了半天没看懂,后来 http://www.careercup.com/question?id=4425679大概明白题意

弄清题意在做,否则离题千里!!

意思是输入数字n,输出第n 个序列。第一个序列为 1 ,第二个由第一个产生11(1个1),下一个为21(2个1),下一个为1211(1个2,1个1)。。依次下去。明白题意后就不是很难了。迭代生成。

string countAndSay(int n) 
    {
        if(n <= 0) return string();
        
        string start_str = "1";
        
        if(n == 1) return start_str;
        
        while( n > 1)
        {
           start_str = get_next_str(start_str); //每次获取下一个
           --n;
        }
        
        return start_str;
    }
    //字符串用string处理,如此处理不是很好,但是大小有不清楚。
    string get_next_str(string &str)//此函数相当于字符串压缩
    {
        int count = 1;//开始想用char型直接加1操作,后来一想,万一溢出很难查
        int pos = 0;
        string res;
        while(str[pos] != '\0')
        {
            if(str[pos] != str[pos+1])
            {
                string count_str;
                stringstream str_stream;
                str_stream<<count;
                str_stream>>count_str;
                
                res = res+count_str+str[pos];
                count = 1;
            }
            else
            {
                count ++;
            }
            pos++;
        }
        
        return res;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值