1, 11, 21, 1211, 111221, ...
Given an integer n, generate the nth sequence.
這題是easy題,但我不知不覺又做了一個(gè)小時(shí)..感覺我的精神是游離的..一旦遇到思維困難就常常陷入一種不思進(jìn)取的狀態(tài),然后不斷自我懷疑....這種習(xí)慣是需要替換的。即便做不出來不要一直呆在那里想呀。
這題要維護(hù)兩個(gè)string,第i個(gè) 和第i-1個(gè)sequence。巧妙的地方是for循環(huán)外面的部分,是處理最后1位或者n位數(shù)字的。所以我覺得這題思維難度還是有的。注意每次結(jié)束后或者開始前count要置1。
public String countAndSay(int n) {
StringBuilder res = new StringBuilder();
res.append("1");
int count = 1;
int i = 1;
while (i < n) {
StringBuilder sb = new StringBuilder();
for (int j = 1; j < res.length(); j++) {
if (res.charAt(j) == res.charAt(j - 1)) {
count++;
} else {
sb.append(count);
sb.append(res.charAt(j - 1));
count = 1;
}
}
sb.append(count);
//count 每次都要置1
count = 1;
sb.append(res.charAt(res.length() - 1));
res = sb;
i++;
}
return res.toString();
}