LeetCode Count and Say
2015-09-18 11:32
387 查看
原题链接在这里:https://leetcode.com/problems/count-and-say/
当前的读音用来做数列的下一个"1" 读成1个1,写成"11"用来作为下一个。
从i = 2开始一直到n作为外层loop, i是第 ith 个结果。
进入循环后,新生成count = 1, index = 1, 然后进入内层loop, 用index 从第二位走res, 现字符等同于前字符就count++, 不同字符就先append count, 然后 append 前字符,然后count归为1. 走完内层loop, 再把最后一段的count, 字符加到StringBuilder中。
Note: count, StringBuikder,index 都需要在外层循环归回原数。
AC Java:
当前的读音用来做数列的下一个"1" 读成1个1,写成"11"用来作为下一个。
从i = 2开始一直到n作为外层loop, i是第 ith 个结果。
进入循环后,新生成count = 1, index = 1, 然后进入内层loop, 用index 从第二位走res, 现字符等同于前字符就count++, 不同字符就先append count, 然后 append 前字符,然后count归为1. 走完内层loop, 再把最后一段的count, 字符加到StringBuilder中。
Note: count, StringBuikder,index 都需要在外层循环归回原数。
AC Java:
public class Solution { public String countAndSay(int n) { if(n<=0){ return ""; } if(n==1){ return "1"; } String res = "1"; for(int i = 2; i<=n; i++){ int count = 1; StringBuilder sb = new StringBuilder(); int index = 1; for( index = 1; index<res.length(); index++){ if(res.charAt(index) == res.charAt(index-1)){ count++; }else{ sb.append(count); sb.append(res.charAt(index-1)); count = 1; } } sb.append(count); sb.append(res.charAt(index-1)); res = sb.toString(); } return res; } }
相关文章推荐
- Debug HDFS (远程调试HDFS)
- 彻底搞定C语言指针(转)
- java中static 和 final
- [!] Unable to satisfy the following requirements:众里寻他千百度。
- LeetCode Count and Say
- ios - 网络检测
- 清理内存clear
- ecshop 的transport.js 与jqueyr冲突
- 让你达到年薪40万的必备运维思想!
- getAttribute与getParameter
- 学习网址
- List集合排序
- 数据结构实验二:双向链表
- Ext之表单
- 解决 IE7 中 display:inline-block 失效的问题
- 【JAVASCRIPT】React学习- 与 flux 结合使用
- Unity3D中关于场景销毁时事件调用顺序的一点记录
- linux中 sh 与 ./ filename 命令
- iOS9 适配教程
- git--多人开发