Question
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.
Notice
The sequence of integers will be represented as a string.
Example
Given n = 5 , return "111221" .
Thinking
Tested on leetcode, error input (n < 1) always return “1”.
Solution
Java (Passed on leetcode)
public class Solution {
public String countAndSay(int n) {
if (n < 1) {
return "1";
}
String say = "1";
int k = 2;
while (k <= n) {
String sayExtra = say + "$"; // add an extra char to help handle last char.
char pre = say.charAt(0);
int count = 1;
String tmpStr = "";
for (int i = 1; i < sayExtra.length(); i++) {
if (pre == sayExtra.charAt(i)) {
++count;
} else {
tmpStr = tmpStr + count + pre;
count = 1;
pre = sayExtra.charAt(i);
}
}
say = tmpStr;
++k;
}
return say;
}
}
Java
public class Solution {
/**
* @param n the nth
* @return the nth sequence
*/
public String countAndSay(int n) {
// Write your code here
String cas = "1";
for (int i = 2; i <= n; i++) {
String cas2 = "";
int count = 1;
char pre = cas.charAt(0);
for (int j = 1; j < cas.length(); j++) {
if (pre == cas.charAt(j)) {
++count;
} else {
cas2 = cas2 + count + pre;
pre = cas.charAt(j);
count = 1;
}
}
cas = cas2 + count + pre;
}
return cas;
}
}