Problem:
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"
Or11
.
11
is read off as"two 1s"
Or21
.
21
is 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.
Solution: Query the number of occurrences of each character in turn, and count down, and then deposit in the results, the problem data is smaller.
The main topic: according to the sequence of the previous string, to count the number of occurrences of each character and what character, such as the first is 1, then the second is the description of the first string: 1 1=11
Java source Code (208MS):
public class Solution {public String countandsay (int n) { char[] seq=new char[100000]; Char[] Bak=new char[100000]; Char[] tmp; Char T; int top=1,index,l,r,num; seq[0]= ' 1 '; seq[1]=0; while (--n >0) { index=0; for (int i=0;i<top;i++) { num=1; while (I+1<top && seq[i+1]==seq[i]) {i++;num++;} L=index; while (num>0) { bak[index++]= (char) (num%10+ ' 0 '); num/=10; } r=index-1; while (l<r) {t=bak[l];bak[l]=bak[r];bak[r]=t;l++;r--;} Bak[index++]=seq[i]; } Top=index; tmp=seq;seq=bak;bak=tmp; } return new String (seq,0,top);} }
C Language Source code (0MS):
char* Countandsay (int n) { char* seq= (char*) malloc (sizeof (char) *100000); char* bak= (char*) malloc (sizeof (char) *100000); char* tmp; Char T; int top=1,i,index,num,l,r; seq[0]= ' 1 '; seq[1]=0; while (--n) { index=0; for (i=0;i<top;i++) { num=1; while (I+1<top && seq[i+1]==seq[i]) { i++; num++; } L=index; while (num>0) { bak[index++]=num%10+ ' 0 '; num/=10; } r=index-1; while (l<r) { t=bak[l];bak[l]=bak[r];bak[r]=t;l++;r--; } Bak[index++]=seq[i]; } bak[index]=0; Top=index; tmp=seq;seq=bak;bak=tmp; } Free (bak); return seq;}
C + + source code (0MS):
Class Solution {public: string Countandsay (int n) { char* seq= (char*) malloc (sizeof (char) *100000); char* bak= (char*) malloc (sizeof (char) *100000); char t,*tmp; int l,r,index,top=1,i,num; seq[0]= ' 1 '; seq[1]=0; while (--n) { index=0; for (i=0;i<top;i++) { num=1; while (I+1<top && seq[i+1]==seq[i]) {i++;num++;} L=index; while (num>0) { bak[index++]=num%10+ ' 0 '; num/=10; } r=index-1; while (l<r) {t=bak[l];bak[l]=bak[r];bak[r]=t;l++;r--;} Bak[index++]=seq[i]; } bak[index]=0; Top=index; tmp=seq;seq=bak;bak=tmp; } return string (seq);} ;
Python source code (64MS) Data volume hours are available, the data is large, the following three kinds of reference:
Class solution: # @param {integer} n # @return {string} def countandsay (self, N): seq=[' 1 '];top=1; While n-1>0: n-=1;index=0;bak=[] i=0 while i<top: num=1 while i+1<top and seq[i+1]== Seq[i]:i+=1;num+=1 bak.append (Chr (Num+ord (' 0 ')) bak.append (Seq[i]) i+=1 Seq=bak;top=len ( BAK) return '. Join (SEQ)
Leetcode Count and Say (C,c++,java,python)