[leetcode]Count and Say

原題:函數

  The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ...code

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.
blog

 題意大體意思是根據每一個數字的多少構成下一個數字,解題關鍵在於對每一位的數字進行標記,明確每一個數字出現次數,這樣 次數+數字構成下一次數字。leetcode

      該代碼思路思路比較直接,經過統計數字的個數進行輸出。get

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]!='\0')//不是最後一個字符
               {
                 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函數的,簡潔很多。string

     

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(); } };

  兩種思路的驗證結果是相同的。io

        

   結論:利用STL提升代碼可讀性和效率;class

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

相關文章
相關標籤/搜索