题目描述:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.
Given an integer n, generate the n th sequence.
Note: The sequence of integers will be represented as a string.
思路解析:
- 首先需要判断n的合法性
- 然后需要计数,初始化第一个curStr为“1”,计数从1开始
- 对上一个string进行遍历计数,如果计数完毕,就把count加入到新的字符串中,记得把count设置为1;
- 遍历完毕前一个字符串后,记得把最后一个count和最后一个字符加入到下一个字符串,开始的位置增加1
代码:
public class Solution {
public String countAndSay(int n) {
if(n<0)
return "";
String curRes = "1";
int start =1,i;//注意i声明在外边哦
while(start<n){
StringBuilder res = new StringBuilder();
int count =1;
for(i=1;i<curRes.length();i++){
if(curRes.charAt(i)==curRes.charAt(i-1)){//计数有多少个相同的字符
count++;
}else{
res.append(count);//没有相等的了就要加入新的字符串中了
res.append(curRes.charAt(i-1));
count=1;
}
}
res.append(count);
res.append(curRes.charAt(i-1));
curRes = res.toString();
start++;
}
return curRes;
}
}