Skip to content

Commit 2e23e89

Browse files
committed
add Count and Say
1 parent 9d7c999 commit 2e23e89

2 files changed

Lines changed: 76 additions & 0 deletions

File tree

zh-cn/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
* [Space Replacement](string/space_replacement.md)
3636
* [Wildcard Matching](string/wildcard_matching.md)
3737
* [Length of Last Word](string/length_of_last_word.md)
38+
* [Count and Say](string/count_and_say.md)
3839
* [Integer Array](integer_array/README.md)
3940
* [Remove Element](integer_array/remove_element.md)
4041
* [Zero Sum Subarray](integer_array/zero_sum_subarray.md)

zh-cn/string/count_and_say.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Count and Say
2+
3+
## Source
4+
5+
- leetcode: [Count and Say | LeetCode OJ](https://leetcode.com/problems/count-and-say/)
6+
- lintcode: [(420) Count and Say](http://www.lintcode.com/en/problem/count-and-say/)
7+
8+
```
9+
The count-and-say sequence is the sequence of integers beginning as follows:
10+
11+
1, 11, 21, 1211, 111221, ...
12+
13+
1 is read off as "one 1" or 11.
14+
15+
11 is read off as "two 1s" or 21.
16+
17+
21 is read off as "one 2, then one 1" or 1211.
18+
19+
Given an integer n, generate the nth sequence.
20+
21+
Example
22+
Given n = 5, return "111221".
23+
24+
Note
25+
The sequence of integers will be represented as a string.
26+
```
27+
28+
## 题解
29+
30+
题目大意是找第 n 个数(字符串表示),规则则是对于连续字符串,表示为重复次数+数本身。
31+
32+
### Java
33+
34+
```java
35+
public class Solution {
36+
/**
37+
* @param n the nth
38+
* @return the nth sequence
39+
*/
40+
public String countAndSay(int n) {
41+
if (n <= 0) return null;
42+
43+
String s = "1";
44+
for (int i = 1; i < n; i++) {
45+
int count = 1;
46+
StringBuilder sb = new StringBuilder();
47+
int sLen = s.length();
48+
for (int j = 0; j < sLen; j++) {
49+
if (j < sLen - 1 && s.charAt(j) == s.charAt(j + 1)) {
50+
count++;
51+
} else {
52+
sb.append(count + "" + s.charAt(j));
53+
// reset
54+
count = 1;
55+
}
56+
}
57+
s = sb.toString();
58+
}
59+
60+
return s;
61+
}
62+
}
63+
```
64+
65+
### 源码分析
66+
67+
字符串是动态生成的,故使用 StringBuilder 更为合适。注意s 初始化为"1", 第一重 for循环中注意循环的次数为 n-1.
68+
69+
### 复杂度分析
70+
71+
72+
73+
## Reference
74+
75+
- [[leetcode]Count and Say - 喵星人与汪星人](http://huntfor.iteye.com/blog/2059877)

0 commit comments

Comments
 (0)