Skip to content

Commit 42617eb

Browse files
author
wangpeng
committed
feat(EASY): add _38_countAndSay
1 parent fdb9fb7 commit 42617eb

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package pp.arithmetic.leetcode;
2+
3+
/**
4+
* Created by wangpeng on 2019-05-14.
5+
* 38. 报数
6+
* <p>
7+
* 报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
8+
* <p>
9+
* 1. 1
10+
* 2. 11
11+
* 3. 21
12+
* 4. 1211
13+
* 5. 111221
14+
* 1 被读作 "one 1" ("一个一") , 即 11。
15+
* 11 被读作 "two 1s" ("两个一"), 即 21。
16+
* 21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。
17+
* <p>
18+
* 给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
19+
* <p>
20+
* 注意:整数顺序将表示为一个字符串。
21+
* <p>
22+
* <p>
23+
* <p>
24+
* 示例 1:
25+
* <p>
26+
* 输入: 1
27+
* 输出: "1"
28+
* 示例 2:
29+
* <p>
30+
* 输入: 4
31+
* 输出: "1211"
32+
*
33+
* @see <a href="https://leetcode-cn.com/problems/count-and-say/">count-and-say</a>
34+
*/
35+
public class _38_countAndSay {
36+
37+
public static void main(String[] args) {
38+
_38_countAndSay countAndSay = new _38_countAndSay();
39+
System.out.println(countAndSay.countAndSay(4));
40+
System.out.println(countAndSay.countAndSay(5));
41+
System.out.println(countAndSay.countAndSay(6));
42+
}
43+
44+
/**
45+
* 解题思路:
46+
* 本题的难点在于:报数的概念理解,至少我从题意中没有很清晰的理解,但是感觉像是个递推式
47+
* 从4->5分析,将4个每一位拆开看(个数+数字),4=1211 => 1=11,2=12,11=21,所以5=111221
48+
* 所以解题用循环,从1->n可求解出来
49+
*
50+
* @param n
51+
* @return
52+
*/
53+
public String countAndSay(int n) {
54+
String str = "1";
55+
for (int i = 2; i <= n; i++) {
56+
StringBuilder builder = new StringBuilder();
57+
char pre = str.charAt(0);
58+
int count = 1;
59+
for (int j = 1; j < str.length(); j++) {
60+
char c = str.charAt(j);
61+
if (c == pre) {
62+
count++;
63+
} else {
64+
builder.append(count).append(pre);
65+
pre = c;
66+
count = 1;
67+
}
68+
}
69+
builder.append(count).append(pre);
70+
str = builder.toString();
71+
}
72+
73+
return str;
74+
}
75+
}

0 commit comments

Comments
 (0)