Open lpatmo opened 5 years ago
/**
* @param {number} n
* @return {string}
*/
var countAndSay = function(n) {
let sequence = "1";
let newTerm = "";
for (let i = 2; i < n+1; i++) {
for (let start = 0; start < sequence.length; start++) {
//check if there are at least two characters
if (start+1 < sequence.length) {
let window = sequence.substring(start, start+2);
if (window === "11") {
newTerm += "21";
start+=1;
} else if (window === "21") {
newTerm += "1211"
start+=1;
} else if (window[0] === "1") {
newTerm += "1"
}
} else if (sequence[start] === "1") {
newTerm += "11"
}
}
sequence = newTerm;
newTerm = "";
}
return sequence;
};
Note: this solution comes close (up to level 4), but doesn't pass an input of 5.
The count-and-say sequence is the sequence of integers with the first five terms as following:
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1 Output: "1" Example 2:
Input: 4 Output: "1211"