[LeetCode] Count and Say

来源:互联网 发布:windows 2008 加入域 编辑:程序博客网 时间:2024/06/16 12:15

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.

  • 题意: 读数字,开始是1,然后是两一个一(1 1),然后是两个一(2 1),然后是一个二一个一(1 2 1 1).求第n次的结果,存成字符串返回.
  • 解法: 嘛,其实感觉这题没意思,因为数字太大的话,时间会很长.数据小的话,就没意思了,因为数字的连续数量不会超过9个,总之,直接模拟就好了,用两个串来记当前串和下一串,读当前串结果存在下一串,然后读下一串,读的过程就是两个for循环,第一重是枚举第i个数,然后跳到下一个与i不同的数,第二重就是一直循环把相同的数跑完就好了,然后用j-i得出连续的数有多少个.复杂度:O(n*m)m在递增,一次比一次长.数据大概应该是只有1到18吧.18组测试数据.
class Solution {public:    string countAndSay(int n) {        string akResult[2];        int iCurIdx = 0;        for (akResult[iCurIdx].push_back('1'); --n; iCurIdx ^= 1) {            akResult[iCurIdx ^ 1].clear();            for (int i = 0, j = 0; i < (int)akResult[iCurIdx].size(); i = j) {                for (j = i; j < (int)akResult[iCurIdx].size() && akResult[iCurIdx][j] == akResult[iCurIdx][i]; ++j);                akResult[iCurIdx ^ 1].push_back((j - i) + '0');                akResult[iCurIdx ^ 1].push_back(akResult[iCurIdx][i]);            }        }        return akResult[iCurIdx];    }};

欢迎访问我的github,我的leetcode持续更新: https://github.com/tsfissure/LeetCode

0 0