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.

    题目看了半天,对自己的汉语水平狠狠的质疑了一把,然后开始写代码。

    string countAndSay1(int n) 
    {
        if(n<=0)
            return "";
        string str="1";
        for(int i =1;i<n;i++)
        {
            int count=0;
            string tmp="";
            for(int j =0,k=0;k<str.size();k++)
            {
                char chj=str[j];
                char chk=str[k];
                if(chj==chk)
                    count++;
                else
                {
                    tmp=tmp+(char)(count+'0')+chj;
                    j=k;
                    count=1;
                }
            }
            tmp=tmp+(char)(count+'0')+str[str.size()-1];
            str = tmp;
        }
        return str;
    }

    完了再去看别人写的代码,发现差距还是有的,自己这乱糟糟的风格,简单的东西非要那么复杂干什么。。自己努力学着点,学着短小精悍!

    string s = "1";
        for(int i = 1; i < n; ++ i)
        {
            int count = 1;
            string temp = "";
            for(int j = 1; j < s.size(); ++ j)
            {
                if(s[j] == s[j - 1])
                    ++ count;
                else
                {
                    temp = temp + (char)(count + '0') + s[j - 1];
                    count = 1;
                }
            }
            s = temp + (char)(count + '0') + s[s.size() - 1];
        }
        return s;
  • 相关阅读:
    小白扫盲之-计算机为何需要内存
    Centos 安装Pycharm 并移动到桌面。
    Docker守护进程
    插入排序
    快速排序
    归并排序
    __metaclass__方法
    Python面向对象(2)类空间问题以及类之间的关系
    Python面向对象(1)_初步认识
    python语法基础(8)_包
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4396217.html
Copyright © 2011-2022 走看看