Leetcode Count and Say

Source: Internet
Author: User

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

1is read off as "one 1" or 11 .
11is read off as "two 1s" or 21 .
21is read off "one 2 as, then one 1" or 1211 .

Given an integer n, generate the nth sequence.

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

Read the other people's explanations on the internet to understand

1 read into a 1 11

11 read two X 1 21

21 read into a 21 1 1211

1211 read it into a 11 22 x 1 111221

Code implementation

     PublicString Countandsay (intN) {intI=1; String result= "1";  while(i<N) {result=countandsaystring (Result); I++; }        returnresult; }     Publicstring countandsaystring (String str) {if(Str.equals ("1"))            return"11"; CharCur=str.charat (0);//Current number        intCount=1;//Current number of numbersStringBuilder stringbuilder=NewStringBuilder ();  for(intI=1;i<str.length (); i++)        {            if(cur==Str.charat (i)) {Count++; if(I==str.length ()-1) {stringbuilder.append (count). append (cur); }            }            Else{stringbuilder.append (count). append (cur); Cur=Str.charat (i); Count=1; if(I==str.length ()-1) {stringbuilder.append (count). append (cur); }            }        }        returnstringbuilder.tostring (); }

Leetcode Count and Say

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.