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不相等的位置

          

  • 相关阅读:
    BFS(广度优先搜索)
    有源点最短路径--Dijkstra算法
    DFS(深度优先搜索)
    循环双链表基本操作
    有向图的邻接表
    无向网的邻接矩阵
    双链表的基本运算
    项目环境搭建【Docker+k8s】十 || kubernetes资源配置运行容器
    项目环境搭建【Docker+k8s】九 || kubernetes创建容器
    项目环境搭建【Docker+k8s】八 || kubernetes集群部署
  • 原文地址:https://www.cnblogs.com/zhanjxcom/p/5639087.html
Copyright © 2011-2022 走看看