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類,不能被繼承。是不可變對(duì)象,修改值需要?jiǎng)?chuàng)建新的對(duì)象,然后保存新的值,舊的對(duì)象垃圾回收,影響性能:在字符串鏈接的時(shí)候,也需要建立一個(gè)StringBuffer,然后調(diào)用append(),最后StringBuffer toString()。
StringBuffer是可變對(duì)象,修改時(shí)不需要重新建立對(duì)象。
初始創(chuàng)建需要construction: StringBuffer sb = new StringBuffer();,初始保存一個(gè)null。賦值的時(shí)候可以使用sb.append();,不可以直接用賦值符號(hào):sb="***"; //error。