[leetcode] 38. Count and Say 解题报告

题目链接:https://leetcode.com/problems/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.


思路:本题的意思是用一个计数+字符来编码一个数字,接着再用计数+字符编码上一个结果,这样会形成一个序列。最后将结果保存到字符串中。

因为涉及到整数和字符串之间的转换,STL提供了一个专门用于各类型转换的类stringstream,有了这个类之后妈妈再也不用担心类型之间的转换了。

代码如下:

#incldue <stdlib.h>
class Solution {
public:
    string countAndSay(int n) {
        string result = "1";
        int cnt = 1;
        while(cnt < n)
        {
            stringstream tem;//c++处理各类型转换的一个stl类
            char old = '#';
            int num = 0;
            for(int i = 0; i <result.size() ; i++)
            {
                if(result[i] != old)//本字符和前一个字符不相等
                {
                    if(old != '#')//判断是否第一个字符
                        tem << num << old;
                    num = 1;
                    old = result[i];
                }
                else//本字符和之前一个相等,计数加1
                    num++;
            }
            tem << num << old;//将数字和字符输入到容器中
            tem >> result;//将容器中的字符串输出到结果中
            cnt++;
        }
        return result;
    }
};


你可能感兴趣的:(LeetCode,算法,String)