# 38 Count and Say

真的寫下來,歸納邏輯後再寫成程式比較聰明

LeetCode

he 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.

input: 一個數字
output: 印出這個序列,從 1 開始
Example 1:

Input: 1
Output: "1"
Example 2:

Input: 4
Output: "1211"


Think Two Pointer
*/

/**
 * @param {number} n
 * @return {string}
 */
var countAndSay = function(n) {}

Edge Case

負數 ?

怎麼解

看題目之後我歸納出 "數目" “值”,並用 Two Pointer,ind 遍歷一次,當 ind 跟 pointer 不一樣則輸出一次 "數目" “值”

  • 數目: ind - pointer

  • 值 n [pointer]

let pointer = 0;
let result = '';
for(let ind = 1; ind <= str.length; ind++){
    if(str[pointer] !== str[ind]){
        // 長度
        let len = ind - pointer;
        // 印出來
        result = result + len + str[pointer];
        // 繼續下一輪收尋
        pointer = ind;
    }
}
return result;

input 是數字,所以最後的程式碼是

var countAndSay = function(n) {

    let start = '1';
    for(let i=1; i < n; i++){
        start = generateStr(start);
    }

    return start;

    function generateStr(str){
      let pointer = 0;
      let result = '';
      for(let ind = 1; ind <= str.length; ind++){
        if(str[pointer] !== str[ind]){
          let len = ind - pointer;
          result = result + len + str[pointer];
          pointer = ind;
        }
      }
      return result;
    }
    
};

console.log(countAndSay(4)) // 1211
//  faster than 91.48% of JavaScript online submissions

學到什麼

  • 真的寫下來,歸納邏輯後再寫成程式比較聰明

  • submission 速度好像不太準 XD 第一次才 34% 第二次變 91%... 也差太多了明明都是同一份 code

Last updated