zoukankan      html  css  js  c++  java
  • [leetcode] Count and Say

    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.

    思路:

    举例说明怎么做,求 s=1211 的下一个,用res记录。从下标1开始遍历这个字符串,下标0作为比较字符。将s[1]与s[0]比较,不等,于是s[0]只重复了一次,因此就是1个s[0],此时res=11。再将s[2]与s[1]比较,还是不等,res=1112。s[3]与s[2]比较,相等,即s[2]重复了两次,也就是2个s[2],此时res=111221。有一个需要注意的地方,遍历s的时候最后添加的是倒数第二个不重复的字符,最后的那些重复的字符只是与前面进行比较并没有添加到res中。因此在遍历完成后,还需要添加最后那些重复的字符。

    题解:

    class Solution {
    public:
        string fun(string s) {
            string str;
            int count = 1;
            char pre = s[0];
            char tmp;
            for(int i=1;i<s.size();i++) {
                if(s[i]==pre)
                    count++;
                else {
                    tmp = count+'0';
                    str = str+tmp+pre;
                    count = 1;
                    pre = s[i];
                }
            }
            tmp = count+'0';
            str = str+tmp+pre;
            return str;
        }
        string countAndSay(int n) {
            string res = "1";
            for(int i=1;i<n;i++)
                res = fun(res);
            return res;
        }
    };
    View Code
  • 相关阅读:
    java作业利用递归解决问题
    java课堂测试2(两种方式)
    java模拟验证码生成
    java选做猜数字
    java课堂动手测试
    java课堂作业,求多参数的和
    《大道至简》第一章伪代码形式读后感
    《大道至简》读后感
    关于《大道至简》第八章的收获
    [JLOI2012]树 倍增优化
  • 原文地址:https://www.cnblogs.com/jiasaidongqi/p/4235447.html
Copyright © 2011-2022 走看看