leetcode第38题-Count and Say
来源:互联网 发布:ubuntu 网络文件夹 编辑:程序博客网 时间:2024/06/05 09:42
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.
题目要求:主要是数数,但是题目要求是输出第n个字符串,即如果输入5,则输出字符串111221。
分析:按照题意,可以首先定义两个字符串,一个用来表示当前cur,一个用来表示进阶到的下一个tmp,然后遍历时每遇到相同的就使count++,然后就用'0'+count表示这个数有几个。
完整代码:
#include<stdio.h>#include<stdlib.h>#include<string.h>char* countAndSay(int n) { if(n==1)return "1";char *cur=(char*)malloc(sizeof(char)*2),*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;}
1 0
- leetcode第38题-Count and Say
- leetcode 第38题:Count and Say
- 【leetcode】第38题 Count and Say 题目+解析+代码
- leetcode-38-Count and Say 基础题
- [LeetCode 38] Count and Say
- LeetCode(38) Count and Say
- [leetcode 38] Count and Say
- [Leetcode] 38 - Count and Say
- leetcode-38 count and say
- [LeetCode 38]Count and Say
- LeetCode 38 Count and Say
- leetcode-38 Count and Say
- Leetcode 38 Count and Say
- Leetcode---(38)Count and Say
- leetcode 38: Count and Say
- Leetcode# 38 Count and Say
- leetcode[38]:Count and Say
- leetcode-38 Count And Say
- JavaScript之DOM总结
- 2015.6.14用文件保存学生名单
- LINUX7(CentOS7)上安装Oracle 12C
- swift func
- 【iOS官方文档翻译】iOS蓝牙的基本概念
- leetcode第38题-Count and Say
- C语言基础(linux)
- 微博项目
- UVA11992:Fast Matrix Operations(线段树)
- 一起学习CC3200系列教程之2个TCP_非阻塞及阻塞设置
- ubuntu 安装Tkinter, ImageTk...
- 【PAT】自测2 素数对猜想
- Android模拟器按键对应的键盘按键
- 使用Google CPU Profiler对C/C++多线程程序做性能剖析