LeetCode——Count and Say
来源:互联网 发布:对外经济贸易大学知乎 编辑:程序博客网 时间:2024/05/24 07:23
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.
"Count and Say problem" Write a code to do following:
n String to print
0 1
1 1 1
2 2 1
3 1 2 1 1
...
Base case: n = 0 print "1"
for n = 1, look at previous string and write number of times a digit is seen and the digit itself. In this case, digit 1 is seen 1 time in a row... so print "1 1"
for n = 2, digit 1 is seen two times in a row, so print "2 1"
for n = 3, digit 2 is seen 1 time and then digit 1 is seen 1 so print "1 2 1 1"
for n = 4 you will print "1 1 1 2 2 1"
Consider the numbers as integers for simplicity. e.g. if previous string is "10 1" then the next will be "1 10 1 1" and the next one will be "1 1 1 10 2 1"
Java代码:
public class Solution { public String countAndSay(int n) { if (n < 1) return null; String str = "1"; StringBuilder sb = new StringBuilder(); for(int j = 2; j <= n; j++) { int count = 1; for (int i = 1; i < str.length(); i++) { if (str.charAt(i) == str.charAt(i - 1)) { count++; } else { sb.append(count); sb.append(str.charAt(i-1)); count = 1; } } sb.append(count); sb.append(str.charAt(str.length() - 1)); str = sb.toString(); sb.setLength(0); } return str; }}
- leetcode ——Count and Say
- LeetCode——Count and Say
- LeetCode——Count and Say
- leetcode记录——Count and Say
- leetcode 038 —— 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
- LeetCode: Count and Say
- st2---cocos2dx
- Word Break II
- 汇编器源码剖析
- emacs在mac上使用
- 百度实习面试
- LeetCode——Count and Say
- Leetcode: Trapping Rain Water
- git reset-----git 本地仓库回退
- 锐捷5.20代理检测之ACK响应报文检测
- c和指针 03
- misc_register、 register_chrdev 的区别总结
- JSON入门
- 修改wamp中mysql的默认密码
- solaris 系统信息查看