Q:
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11
11 is read off as "two 1s" or 21
21 is read off as "one 2, then one 1" or 1211
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
A:
public class Solution {
public String countAndSay(int n) {
StringBuffer sb = new StringBuffer("1");
for(int i = 1; i < n; i++) {
int count = 1;
StringBuffer temp = new StringBuffer();
int len = sb.length();
for(int j = 1; j < len; j++) {
if(sb.charAt(j) != sb.charAt(j - 1)) {
temp.append(count);
temp.append(sb.charAt(j - 1));
count = 1;
}
else {
count++;
}
}
temp.append(count);
temp.append(sb.charAt(len - 1));
sb = temp;
}
return sb.toString();
}
}
String vs StringBuffer:
String是final類,不能被繼承邓了。是不可變對象,修改值需要創(chuàng)建新的對象惧磺,然后保存新的值饵逐,舊的對象垃圾回收,影響性能:在字符串鏈接的時候袱贮,也需要建立一個StringBuffer传惠,然后調用append()迄沫,最后StringBuffer toString()。
StringBuffer是可變對象卦方,修改時不需要重新建立對象羊瘩。
初始創(chuàng)建需要construction: StringBuffer sb = new StringBuffer();
,初始保存一個null盼砍。賦值的時候可以使用sb.append();
尘吗,不可以直接用賦值符號:sb="***"; //error
。