LeetCode(51)- Count and Say
2016-04-12 16:57
225 查看
题目:
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.
思路
题意:给定一个整数字符串,下一个是对上一个的描述,比如”11122211“,下一个是3个1,3个2,2个1,是”313221“,给定n,求出第n个整数字符串关键在于找到当前和前一个的关系,比较一个整数字符串的元素,紧邻是否相同,用变量num统计连续相同的个数,当不想同时候,stringBuffer.append(num).append(元素),num= 1;相同时,num++;
-
代码:
public class Solution { public String countAndSay(int n) { String str = "1"; for(int i = 1;i < n;i++){ int num = 1; StringBuffer sb = new StringBuffer(); for(int j = 1;j < str.length();j++){ if(str.charAt(j) == str.charAt(j-1)){ num++; }else{ sb.append(num).append(str.charAt(j-1)); num = 1; } } sb.append(num).append(str.charAt(str.length()-1)); str = sb.toString(); } return str; } }
相关文章推荐
- 字符串&malloc&strlen&strcpy
- android activity单实例化
- 重载运算符
- Linux进程创建fork()与vfork()
- 网络:GET 的使用
- 错误:the file 'xxx.app' couldn't be opened because you don't have permission to view it
- iOS多线程编程之NSOperation
- 华为OJ试题整理
- Android Volley完全解析(三),定制自己的Request
- android开发 系统信息相关工具类 权限管理页面
- 支付宝java后台接入简单流程
- 一个MEX程序示例
- Anroid ListView分组和悬浮Header实现
- Oracle 删除重复数据只留一条
- 《区块链:从入门到放弃》之obc安装步骤
- 半年收入超2亿RMB 独立游戏开发者的艰苦创业路
- WEB开发:如何用js来模拟服务器的ajax响应,不依赖服务器来编写前端代码
- 刚换了新账号
- 【CodeForces 628B】 New Skateboard (数学水)
- flask restfull 快速入手