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;
  • 相关阅读:
    四则运算(Android)版
    返回二维数组最大联通子数组的和
    第二阶段每日总结08
    第二阶段每日总结07
    第十三周进度条
    第二阶段每日总结06
    第二阶段每日总结05
    找水王02
    第二阶段每日总结04
    浪潮之巅阅读笔记01
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4396217.html
Copyright © 2011-2022 走看看