zoukankan      html  css  js  c++  java
  • 【LeetCode】38. 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.

    提示:

    此题没有什么特别的技巧,根据题目要求的推导公式递推下去就行了。

    注意:如果仔细思考其中的规律,不难发现不会有同一个数字连续出现4次及以上的情况(原因不妨自己仔细推敲一下)。因此在将字符出现次数的计数器(int型)追加到string当中去的时候,我们可以将它与'0'相加,以此转换为char型,这样子会比用to_string()方法来的速度更快。

    代码:

    class Solution {
    public:
        string countAndSay(int n) {
            if (n == 1) return "1";
            string str = "11";
            string res;
            for (int i = 2; i < n; ++i) {
                char cur = str[0];
                int count = 1;
                res = "";
                for (int j = 1; j < str.size(); ++j) {
                    if (str[j] == cur) {
                        ++count;
                    } else {
                        res += (count+'0');
                        res += cur;
                        cur = str[j];
                        count = 1;
                    }   
                }
                res += (count+'0');
                res += cur;
                str = res;
            }
            return str;
        }
    };
  • 相关阅读:
    HDU_5057_分块
    HYSBZ_2002_分块
    HDU_1166_树状数组
    HDU_5692_dfs序+线段树
    多重背包
    二进制中一的个数
    康托展开
    vector, map, queue,set常用总结
    错误票据
    高精度计算
  • 原文地址:https://www.cnblogs.com/jdneo/p/4764682.html
Copyright © 2011-2022 走看看