題目
報(bào)數(shù)指的是筷狼,按照其中的整數(shù)的順序進(jìn)行報(bào)數(shù)棍潘,然后得到下一個(gè)數(shù)恃鞋。如下所示:
1, 11, 21, 1211, 111221, ...
1 讀作 "one 1" -> 11.
11 讀作 "two 1s" -> 21.
21 讀作 "one 2, then one 1" -> 1211.
給定一個(gè)整數(shù) n, 返回 第 n 個(gè)順序。
** 注意事項(xiàng)
整數(shù)的順序?qū)⒈硎緸橐粋€(gè)字符串亦歉。**
樣例
給定 n =5, 返回"111221"
分析
看過去這道題恤浪,好像很復(fù)雜,其實(shí)仔細(xì)分析肴楷,會發(fā)現(xiàn)思路很清晰水由。不管算第幾個(gè)數(shù),我們都要從第一個(gè)數(shù)算起赛蔫,每個(gè)數(shù)都要根據(jù)前一個(gè)數(shù)算出來砂客。算數(shù)的過程就兩個(gè)點(diǎn)泥张,一個(gè)計(jì)算count,那個(gè)數(shù)出現(xiàn)的次數(shù)鞠值,一個(gè)這個(gè)數(shù)本身媚创,所以兩個(gè)臨時(shí)變量每次都要這兩個(gè)數(shù)就可以。
代碼
public class Solution {
/**
* @param n the nth
* @return the nth sequence
*/
public String countAndSay(int n) {
// Write your code here
String oldString = "1";
while (--n>0){
StringBuilder sb = new StringBuilder();
char[] oldChars = oldString.toCharArray();
for(int i=0;i<oldChars.length;i++){
int count = 1;
while((i+1)<oldChars.length && oldChars[i]==oldChars[i+1]){
count++;
i++;
}
sb.append(String.valueOf(count) + String.valueOf(oldChars[i]));
}
oldString = sb.toString();
}
return oldString;
}
}