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;
        }
    };
  • 相关阅读:
    单元测试,集成测试与系统测试
    关于 单窗口服务模型模拟 进行的小测试
    软件测试新随笔
    白盒测试
    黑盒测试小实验
    JUnit框架初次体验
    等价类划分进阶篇
    等价类划分
    因果图法测试小例
    android中将EditText改成不可编辑的状态
  • 原文地址:https://www.cnblogs.com/jdneo/p/4764682.html
Copyright © 2011-2022 走看看