題目來源:leetcode
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.
/**
* Created by a819 on 2017/8/10.
*/
public class CountandSay {
public String countAndSay(int n) {
String str[]=new String[n];//沒必要都保存
for (int y=0;y<n;y++)
str[y]="";
str[0]="1";
String result="1";
int i=0;
while(i<n-1){
int num=1;
for (int j=1;j<str[i].length();j++){
if (str[i].charAt(j-1)==str[i].charAt(j))
{
num++;
//continue;
}
else {
str[i+1]+=(String.valueOf(num)+str[i].charAt(j-1));
num=1;
}
}
str[i+1]+=(String.valueOf(num)+str[i].charAt(str[i].length()-1));
//result+=" ";
//result+=str[i+1];
result=str[i+1];//只求出第n的序列
i++;
}
return result;
}
/**
* 只記錄前一個狀態,不去記錄每個狀態
* @param n
* @return
*/
public String countAndSay1(int n){
if (n==1)
return "1";
int i=1;
StringBuilder cur=new StringBuilder();//當前的序列
cur.append("1");
while (i<n){
int num=1;
StringBuilder next=new StringBuilder();//下個序列
for (int j=0;j<cur.length();j++){
if (j<cur.length()-1&&cur.charAt(j)==cur.charAt(j+1))
num++;
else{
next.append(String.valueOf(num)).append(cur.charAt(j));
num=1;
}
}
cur=next;
i++;
}
return cur.toString();
}
public static void main(String[] args) {
CountandSay c=new CountandSay();
System.out.println(c.countAndSay1(4));
//String s="jd"+" "+"sds"+String.valueOf(3);
//System.out.println(s);
}
}