题目是让我们求一个序列中的第n个,我们按照规律递推过去就可以。主要就是判断当前字符和前一个字符是否相同。需要注意的是int和char加入String时的格式
public class Solution {
public String countAndSay(int n) {
String in = "1";
String res = "";
for( int i=1;i<n;i++ )
{
in = fun(in);
}
res = in;
return res;
}
String fun( String in )
{
int len = in.length();
int flag=0,count=0;
char pre = 'q';
String res = "";
for( int i=0;i<len;i++ )
{
char temp = in.charAt(i);
if( flag == 1 )
{
if( temp == pre )
{
count++;
}
else
{
res += count;
res += pre;
pre = temp;
count = 1;
}
}
else
{
pre = temp;
count = 1;
flag = 1;
}
}
if( flag == 1 )
{
res += count;
res += pre;
}
return res;
}
}