codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Leetcode] Count and Say #43

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 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 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"

lpatmo commented 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.