Leetcode 38. Count and Say strings

Source: Internet
Author: User

. Count and Say


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

1is read off as"one 1"Or11.
11is read off as"two 1s"Or21.
21is read off as"one 2, thenone 1"Or1211.

Given an integer n, generate the nth sequence.

Note:the sequence of integers would be represented as a string.

According to the law can write the following:

 1.     1 
 2.      11
 3.     21
 4.      1211
 5.     111221 
 6.      312211
 7.     13112221
 8.     1113213211
 9.     31131211131221
 10.   13211311123113112211

Ideas:

1. Replace the storage record result,tmp with 2 strings.

2. record the current value n and get the maximum continuous length m of the current value.

Append "M" to the 3.tmp string and append "n".


Class solution {public:    string countandsay (int n)  {     if  (--n < 0)     return  "";     string result =  "1";     string tmp;  //temporary string      int step = 1;//Step     char cur;    // Current element     while  (n)     {    cur =  result[0];    for  (Int i = 0; i < result.size ();  i++)     {    if  ( i+1 < result.size () &NBSP;&AMP;&AMP;&NBSP;RESULT[I]&NBSP;==&NBSP;RESULT[I&NBSP;+&NBSP;1])     {     step++;    }    else    {     stringstream stepstreAm;    stepstream << step;    string stepstr  = stepstream.str ();     tmp.append (1,stepstr[0]);     Tmp.append (1,cur);     step = 1;    cur = result[i  + 1];    }    }    swap (result,  TMP);    tmp =  "";    n--;    }     return result;    }};


2016-08-10 17:24:26

This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1836606

Leetcode 38. Count and Say strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.