题目:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.
Note: The sequence of integers will be represented as a string.
给定整数n,输出第n个序列。
理解题意:第n个序列是和第n-1个序列有关的。第n-1个序列从左往右,字母个数+字母就得到第n个序列。
public class Solution{
public String countAndSay(int n){
if(n<=0) return "";
String oldString = "1";
while(--n > 0)
{
StringBuilder newString = new StringBuilder();
int count=1;
for(int i=1; i<oldString.length();++i)
{
if(oldString.charAt(i-1)==oldString.charAt(i))
{
++count;
}
else
{
newString.append(count);
newString.append(oldString.charAt(i-1));
count=1;//继续下一个字母的统计
}
}
//最后一个字母的统计,因为for循环中处理流程:当前字母与前一个字母比较,统计的是前一个字母而不是当前字母。
newString.append(count);
newString.append(oldString(charAt(oldString.length()-1)));
oldString = newString.toString();
}
return oldString;
}
}