LeetCode 38 Count and Say(C,C++,Java,Python)

Problem:

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 integern, generate thenthsequence.

Note: The sequence of integers will be represented as a string.

Solution:

依次查询每一个字符出现的次数,并统计下来,然后在结果中存入即可,题目数据量比较小。

题目大意:

根据上一个字符串的序列,来统计每个字符出现的次数和什么字符,比如第一个是1,,那第二个就是对第一个字符串的描述:1个1=11

Java源代码(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语言源代码(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++源代码(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源代码(64ms)数据量小时可用,数据量大的话参照上面三种:

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=0while i<top:num=1while i+1<top and seq[i+1]==seq[i]:i+=1;num+=1bak.append(chr(num+ord('0')))bak.append(seq[i])i+=1seq=bak;top=len(bak)return ''.join(seq)

一个积极奋进的目标,一种矢志不渝的追求。

LeetCode 38 Count and Say(C,C++,Java,Python)

相关文章:

你感兴趣的文章:

标签云: