/**38. Count and Say
* @param n
* @returnString
*/
public String countAndSay(int n) {
if (n == 0)
return "";
else if (n == 1)
return "1";
String ret = "1";
for (int i=2; i<=n; i++) {
String cur = "";
for (int j=0; j<ret.length();) {
int k=j+1;
for (; k<ret.length() && ret.charAt(k)==ret.charAt(k-1); k++);
cur += String.valueOf(k-j) + String.valueOf(ret.charAt(j));
j = k;
}
ret = cur;
}
return ret;
}
改进:
public String countAndSay1(int n) {
if (n == 1) {
return "1";
}
String s = "1";
StringBuffer buffer = new StringBuffer();
int count = 0;
int i;
for (int round = 1; round < n; round++) {
count = 1;
buffer.setLength(0);
for (i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i-1)) {
count++;
} else {
buffer.append(count).append(s.charAt(i-1));
count = 1;
}
}
buffer.append(count).append(s.charAt(i-1));
s = buffer.toString();
}
return buffer.toString();
}
//使用StringBuffer.append;