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

          

  • 相关阅读:
    iOS-25个小技巧
    iOS-UITableView的使用
    iOS-UIPickerView
    iOS-UIStoryboard和UIResponder
    javascript弹出层-DEMO001
    jQuery源码分析-02正则表达式-RegExp-常用正则表达式
    JSON动态生成树
    回顾码农历程总结2013 期待2014
    大数据量分页存储过程效率测试附代码
    关于对象序列化json 说说
  • 原文地址:https://www.cnblogs.com/zhanjxcom/p/5639087.html
Copyright © 2011-2022 走看看