zoukankan      html  css  js  c++  java
  • [leetcode]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.

     题意大致意思是根据每个数字的多少构成下一个数字,解题关键在于对每一位的数字进行标记,明确每个数字出现次数,这样 次数+数字构成下一次数字。

          该代码思路思路比较直接,通过统计数字的个数进行输出。

    class Solution {
    public:
        string read2sayArray(int n)
        {
              string s="1";
              string strtemp;
               char temp;
            for(int i=0;i<n-1;i++)
            {
                int len=1;
               for(size_t i = 0;i<s.size();)
               {
                   if(s[i+len]!='')//不是最后一个字符
                   {
                     if(s[i]==s[i+len])//同一个字符
                      {
                           len=len+1; //继续查看下一个字符
                           continue;
                       }
                     else//不等 输出统计结果
                       {
                          temp=len+'0';
                          strtemp+=temp;
                           strtemp+=s[i];
                         i=i+len;//继续下面的查找
                         len=1;
                       }
                   }
                   else//结束
                   {
                        temp=len+'0';
                        strtemp+=temp;
                         strtemp+=s[i];              
                       len=1;
                       break;
                   }
               }
               s=strtemp;
               strtemp="";
            }
          return s;
        }
    };
    

      在leetcode上面看到直接用STL函数的,简洁不少。

         

    class Solution {
    public:
      string countAndSay(int n)
            {
                string s("1");
                 while (--n)
                    s = getNext(s);
                   return s;
            }
        string getNext(const string &s) {
                   stringstream ss;
                   for (auto i = s.begin(); i != s.end(); ) {
                    auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i));
    //bind1st找到不相等的位置输出
                    ss << distance(i, j) << *i;
    //distance 返回二者迭代器之间距离 i = j; } return ss.str(); } };

      两种思路的验证结果是相同的。

            

       结论:利用STL提高代码可读性和效率;

               find_if(i, s.end(), bind1st(not_equal_to<char>(), *i));查找返回和迭代器i不相等的位置

          

  • 相关阅读:
    Docker是什么
    常用架构模式优缺点
    DDD领域模型自动生成?
    组合数【模板】
    组合数【模板】
    HDU 4800 Josephina and RPG【概率dp】
    HDU 4800 Josephina and RPG【概率dp】
    HDU 4424 Conquer a New Region【并查集】【思维题】
    HDU 4424 Conquer a New Region【并查集】【思维题】
    HDU 4427 Math Magic【dp+优化+滚动数组】【好题】
  • 原文地址:https://www.cnblogs.com/zhanjxcom/p/5639087.html
Copyright © 2011-2022 走看看