Look and say code challenge
This code problem is based on leetcode code challenge 38. count and say. First, let’s go over the question first.
The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = "1"
countAndSay(n)
is the way you would "say" the digit string fromcountAndSay(n-1)
, which is then converted into a different digit string.
To determine how you “say” a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.
For example, the saying and conversion for digit string "3322251"
:
Let go over line by line, so basically look and say sequence is the sequence of numbers starting like, 1 says “one 1” that is equivalent to 11. Now 11 is read as “two 1s” and also 21. Third, 21 is read as “one2, then one 1” or 1211.
- 1 =>“one 1” or 11.
- 11 => “two 1s” or 21.
- 21 => “one 2, then one 1” or 1211.
- 1211 => “one 1, one 2, then two 1s” or 111221.
- 111221 => “three 1s, two 2s, then one 1” or 312211.
Here is the approach, we first put two terms as “1”, and “11” and all other terms are going to using previous terms. So to make the next term using the previous term, we loop check the previous term and while checking a term, we can keep a record of the count of all consecutive characters. For the following sequence that is duplicate, we simply add the sound followed by the character to make the next term.
Below is the sample code.,
var countAndSay = function(n) {
let str = "1"
for(let i = 1; i < n; i++){
let strArray = str.split("")
str = ""
let count= 1
for(let j = 0; j < strArray.length; j++){
if(strArray[j] !== strArray[j + 1]){
str = str + `${count}` + strArray[j]
count = 1
}else {
count++
}
}
}
return str
};console.log(countAndSay(5)) // "111221"// 1 => "1"
// 2 => "11"
// 3 => "21"
// 4 => "1211"
// 5 => "111221"
// 6 => "312211"
// 7 => "13112221"
// 8 => "1113213211"