Count and Say
来源:互联网 发布:python chain函数 编辑:程序博客网 时间:2024/06/16 17:45
这个问题花了好长时间,主要是审题有问题,我理解错了,以为是从前往后读,遇到11就变为21,遇到2就变为12,遇到12就变为1112,所以我以为n=6的结果是2111121211,导致写出的程序总是不能Accept。后来上网搜了一下,才知道我审错题了,原来是遇到x个相同的数字y,就返回xy,所以n=6的正确结果是312211。
思路:这个问题无疑是用递归比较方便,然后的问题就是在一个数字组成的字符串里,把相邻的x个相同数字y的子串变成xy。
实现:
public class Solution { public String countAndSay(int n) { if(1 == n)return "1";if(2 == n)return "11";String origin = countAndSay(n - 1);int count = 1;StringBuffer result = new StringBuffer();for(int i = 0; i < origin.length() - 1; i++) {if(origin.charAt(i) == origin.charAt(i + 1)) {count++;if(origin.length() - 2 == i) {result.append(count);result.append(origin.charAt(i));}} else {result.append(count);result.append(origin.charAt(i));count = 1;if(origin.length() - 2 == i) {result.append(count);result.append(origin.charAt(i + 1));}}}return result.toString(); }}总结:主要是审题要正确!
0 0
- LeetCode: Count and Say
- [LeetCode]Count and Say
- LeetCode Count and Say
- [Leetcode] Count and Say
- Count and Say
- Leetcode: Count and Say
- [LeetCode] Count and Say
- LeetCode Count and Say
- Count and Say
- [38]Count and Say
- Count and Say
- Count and Say
- Count and Say
- [LeetCode]Count and Say
- Count and Say
- Count and Say
- [LeetCode] Count and Say
- LeetCode-Count and Say
- 持续集成(第二版)
- jdbcTemplate和SessionFactory的区别
- C# 两个独立exe程序直接通信
- ViewBadger为其他View添加角标
- 在windows中打开服务的几种方式(
- Count and Say
- JSTL标签
- 十步完全理解SQL
- AdaBoost算法原理
- IOS 闭包
- Maven学习笔记——坐标详解
- 上拉下拉刷新,支持ListView,GridView,ScrollView
- ROM、RAM、Register(酷学玩summer STM32开发板 日记)
- 微信支付SDK(python版)