题目描述
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
题解:
给定一个整数n.查看其前一个数字所表示的字符串的“读法”,例如: 1211: 一个1,一个2,两个1,所以为 111221
关键问题是,如何求一个字符串的“读法”的字符串表示
eg: 1211:遍历到2时,与前面数字不一样,将前面的1以及其出现次数count添加到字符串中,并将count置一,注意这里会将最后一位数字遗漏,所以要单独追加
class Solution {
public String countAndSay(int n) {
if(n<=0)
return null;
String res = "1";
for(int i=2;i<=n;i++){
res = Solve(res);
}
return res;
}
//一个字符串的“读法”字符串表示
public String Solve(String str){
int count = 1; //count初始化为1,因为字符串从第二个开始遍历
StringBuilder builder = new StringBuilder();
for(int i=1;i<str.length();i++){
if(str.charAt(i)==str.charAt(i-1)){
count++;
}else{
//分界线
builder.append(count);
builder.append(str.charAt(i-1));
count = 1;
}
}
builder.append(count);
//i取不到str.length()
builder.append(str.charAt(str.length()-1));
return builder.toString();
}
}