问题描述
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1is read off as"one 1"or 11.
11is read off as"two 1s"or 21.
21is read off as"one 2, thenone 1"or 1211.
Given an integer n, generate the n th sequence.
Note: The sequence of integers will be represented as a string.
问题分析
这题的题意比较难理解:
- n=0, “1”
- n=1, 上述只有一个1,故 “11”
- n=2, 上述有两个1,故 “21”
- n=3, 上述有一个2、一个1, 故“12 11”
- n=4, 上述有1个1、一个2、两个1,故“11 12 21”
理解字符串的规律就和容易做了。
代码实现
public String countAndSay(int n) {
String result = "1";
for (int i = 1; i < n; i++) {
result = countString(result);
}
return result;
}
private String countString(String result) {
char c = result.charAt(0);
int count = 1;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 1; i < result.length(); i++) {
if (result.charAt(i) == c) {
count++;
continue;
} else {
stringBuilder.append(String.valueOf(count) + c);
c = result.charAt(i);
count = 1;
}
}
stringBuilder.append(String.valueOf(count) + c);
return stringBuilder.toString();
}
网友评论