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"
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.
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); } }
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; }
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); } };
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 38 Count and Say(C,C++,Java,Python)
原文地址:http://blog.csdn.net/runningtortoises/article/details/45850189