Leetcode 38th question-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"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.

title: The main number, but the title requirement is to output the nth string, that is, if you enter 5, the output string 111221.

Analysis: According to test instructions, you can first define two strings, one to represent the current cur, one to represent the next level to the first TMP, and then traverse each encounter the same to make count++, and then use the ' 0 ' +count to indicate that the number is several.

Full code:

#include <stdio.h> #include <stdlib.h> #include <string.h>char* countandsay (int n) {    if (n==1) return "1"; char *cur= (char*) malloc (sizeof (char) * *), *tmp;cur[0]= ' 1 ', Cur[1]=0;int len,index,i,j,count;for (i=2;i< =n;i++) {len=strlen (cur); tmp= (char*) malloc (sizeof (char) * (3*len)); memset (Tmp,0,3*len); Count=1;for (index=1,j=0; index<len;index++) {if (cur[index]==cur[index-1]) count++;else{tmp[j++]= ' 0 ' +count;tmp[j++]=cur[index-1];count= 1;}} tmp[j++]= ' 0 ' +count;tmp[j++]=cur[len-1];free (cur); cur=tmp;} return cur;} int main () {    int n;    while (scanf ("%d", &n)!=eof) {printf ("%s\n", Countandsay (n));    }    return 0;}



Leetcode 38th question-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.