Data structure & Algorithm
  • Initial page
  • 1212
  • 121231
  • 2.algorithm
    • 2.1.backtracking
      • 2.1.1.連續序列的排列組合(可能會重複)
      • 2.1.3.一串數列中任取n個數字, 總共有幾種組合
      • 2.1.2.一串數列中取n個數字, 共有幾種組合
    • 2.5.Quick sort
    • 2.6.2.6.廣度優先搜尋 (Breadth-first Search)
    • 2.2.Binary Search
    • 2.1.Backtracking
    • 2.4.河內塔 (Tower of Hanoi)
    • 2.7.動態規劃
    • 2.8.深度優先搜尋 (Depth-first Search)
    • 2.7.二分搜尋法
    • 2.3.分治法 (Divide and Conquer)
  • 2.Count and Say
  • 1.Leetcode Algorithm Practice
  • 2-count-and-say
    • c-solution
    • javascript-solution
  • Algorithm
  • 123
Powered by GitBook
On this page
  • 1.Question
  • 2.想法
  • 3. Solution

Was this helpful?

2.Count and Say

Previous2.3.分治法 (Divide and Conquer)Next1.Leetcode Algorithm Practice

Last updated 5 years ago

Was this helpful?

1.Question

2.想法

  • 看幾層就跑幾次, 每次比較同一層間前後的字元是否相同, 並儲存counter.

3. Solution

  • C solution

      char* countAndSay(int n) {
        char * ary = (char *)malloc(5000 * sizeof(char));
        char * oldAry = (char *)malloc(5000 * sizeof(char));
        n = n -1;
        oldAry[0] = '1';
        ary[0] = '1';
        int round = 0;
        int count = 1;
        int index = 0;
        int len = 1;
    
        while(round < n){
            round = round +1;
            index = 0;
            for(int i = 0 ; i < len; i++){
                if (oldAry[i] == oldAry[i + 1] )
                {
                    //計算重複的數量
                    count = count + 1;        
                }else{
                    //數量 -> 將數字(1~9)轉到字元
                    ary[index++] = count+'0';
                    //什麼數字
                    ary[index++] = oldAry[i];
                    count = 1;    
                }
            }
            //上一次的字元數量
            len = index ;
            //結束字元
            ary[index++] = '\0';
            memcpy(oldAry, ary, len);
    
        }
        free(oldAry);
        return ary;
       }
  • JavaScript solution

          var countAndSay = function(n) {

    res="" oldAry = []; oldAry.push(1) ary = []; ary.push(1) round = 0; count = 1; index = 0; len = 1; while(round < n-1){ round++; index = 0 for(i = 0 ; i < len; i++){ if (oldAry[i] === oldAry[i+1] ) { count++ }else{ ary[index++] = count; ary[index++] = oldAry[i]; count = 1; } } len = index ; oldAry=ary.slice(0) } ary.forEach(function(element, index, array){ res+=element }) return res };

將數字轉為字元