題目描述
count-and-say數(shù)列的前幾項如下:
1, 11, 21, 1211, 111221, ...
1讀作“1個1”或11
11讀作“2個1“或者21
21讀作”1個2撤蚊,1個1“或者1211
給出一個整數(shù)n来庭,請給出序列的第n項
注意:序列中的數(shù)字用字符串表示
分析
- 從上一個數(shù)字辑奈,到下一個數(shù)字阳距,建立一種計算關(guān)系身笤。
- 從1開始計算,計算 n-1 次抽莱,得到第n個數(shù)字。
- 使用 pre 記錄上一位數(shù)字骄恶,使用 count 計算上一位數(shù)字出現(xiàn)次數(shù)食铐。
- 遇到不同于pre的位,將 count + pre 記錄Stringbuffer上僧鲁。
- 遍歷完之后虐呻,產(chǎn)生下一位的字符串。
java 代碼
public class Solution {
public String countAndSay(int n) {
if(n <= 0){
return "";
}
String str = "1";
for(int i = 1; i < n; i++){
int count = 0;
char pre = '*';
StringBuffer sb = new StringBuffer();
for(int j = 0; j < str.length(); j++){
if(str.charAt(j) == pre || pre == '*'){
count ++;
}else{
sb.append(count+Character.toString(pre));
count = 1;
}
pre = str.charAt(j);
}
sb.append(count+Character.toString(pre));
str = sb.toString();
}
return str;
}
}