zoukankan      html  css  js  c++  java
  • 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这个数字产生,得出11,然后21,再然后1211。。。。就是通过上一个字符串中有几个1几个2等等,产生出下一个字符串。每一次对一个字符串循环计数,首先设置一个初始变量,计算第一个数字出现了几次,cont++;如果不等于,在开始将原有字符串中+count+上一次数字,将这个字符赋值给这个变量,count初始化为1,进行下次循环。就可以得到这个字符串应有的结果。

    class Solution {
    public:
        string countSay(const string &str)
        {
            string result;
            char temp=str[0];
            int count=1;
            int n=str.size();
            char count_ch;
            for(int i=1;i<n;i++)
            {
                if(str[i]==temp)
                {
                    count++;
                }
                else
                {
                    count_ch=count+'0';
                    result=result+count_ch+temp;
                    temp=str[i];
                    count=1;
                }
            }
            count_ch=count+'0';
            result=result+count_ch+temp;
            return result;
        }
        string countAndSay(int n) {
            string say="1";
            for(int i=1;i<n;i++)
            {
                say=countSay(say);
            }
            return say;
        }
    };
  • 相关阅读:
    C#生成MD5的方法
    平常心是道
    Android 三种动画的使用 – Tween Animation
    17个Javascript日期选择器
    Javascript解码编码常用函数
    mysql 命令行导入导出数据
    技术驱动还是产品驱动
    Ubuntu 和 Redhat / Fedora 服务管理命令对比表
    jquery常用技巧
    Fedora 17安装JDK1.7
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3681061.html
Copyright © 2011-2022 走看看