Leetcode -- Count and Say
来源:互联网 发布:sql数据库备份软件 编辑:程序博客网 时间:2024/05/29 17:28
问题链接:https://oj.leetcode.com/problems/count-and-say/
问题描述;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.
问题API:public String countAndSay(int n)
问题分析:
没有什么可以取巧的,就是brute force, 从1~n,base case 是”1”,然后第i的结果就由第I – 1的结果根据规则推导得出。
条件是while(n > 1){运算规则, n--} 代码如下:
public String countAndSay(int n) { String res = "1"; while(n > 1){ char cur_bit = res.charAt(0); int counter = 1; StringBuilder next_res = new StringBuilder(); for(int i = 1; i < res.length(); i++){ if(res.charAt(i) == cur_bit){ counter++; }else{ next_res.append("" + counter + cur_bit); cur_bit = res.charAt(i); counter = 1; } } next_res.append("" + counter + cur_bit); res = next_res.toString(); n--; } return res; }
0 0
- LeetCode: Count and Say
- [LeetCode]Count and Say
- LeetCode Count and Say
- [Leetcode] Count and Say
- Leetcode: Count and Say
- [LeetCode] Count and Say
- LeetCode Count and Say
- [LeetCode]Count and Say
- [LeetCode] Count and Say
- LeetCode-Count and Say
- LeetCode: Count and Say
- LeetCode - Count and Say
- [LeetCode] Count and Say
- Count and Say 【leetcode】
- [LeetCode] Count and Say
- Leetcode Count and Say
- LeetCode Count and Say
- LeetCode | Count and Say
- android sim卡 TelephonyManager类:Android手机及Sim卡状态的获取
- 【机器学习快讯】20150128机器学习快讯
- 几句话弄清楚Java参数传值还是传引用
- 【SzNOI语法百题】【d008】 求两数的整数商 和 商
- 客户端与服务器持续同步解析(轮询,comet,WebSocket)
- Leetcode -- Count and Say
- jBPM4.4表结构
- 在xcode中需要用2dx里之前没用过并且未加入搜索路径的文件的设置方法
- C语言及程序设计初步例程-43 从文本文件中读入数据
- Win32程序(二)
- linux oom killer for android
- CODEVS 1011 数的计算
- Cordova配置与开发
- 设计模式(Design Patterns)