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类,不能被继承。是不可变对象,修改值需要创建新的对象,然后保存新的值,旧的对象垃圾回收,影响性能:在字符串链接的时候,也需要建立一个StringBuffer,然后调用append(),最后StringBuffer toString()。
StringBuffer是可变对象,修改时不需要重新建立对象。
初始创建需要construction: StringBuffer sb = new StringBuffer();
,初始保存一个null。赋值的时候可以使用sb.append();
,不可以直接用赋值符号:sb="***"; //error
。