Leetcode - 38. Count and Say

38. Count and Say

題目簡介

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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, generate the nth sequence.

Note: The sequence of integers will be represented as a string.s

解法一:迭代

思路如下:遍歷前一個字符串的字符,若上一個字符和當前字符相等就自增加計數,否則輸出到res中並且初始化計數器。

此種方法同前面去除數組中相同的元素。

string countAndSay(int n) {
        if(n==0) return "";

        string prev = "1";
        string res = "";
        int count=1;
        for(int i=1;i<n;i++){
            for(int j=1;j<=prev.length();j++){
                if(j==prev.length()){
                    cout<<i<<": "<<prev[j]<<endl;
                }
                if(prev[j-1]==prev[j]){
                    count++;
                }else{
                    res += to_string(count);
                    res += prev[j-1];
                    count = 1;
                }
            }

            prev = res;
            res = "";
            /* ~~My Own Stupid Code ~~s
            ch = prev[0];
            count = 1;
            for(int j=1;j<prev.length();j++){
                while(ch==prev[j]){
                    count++;
                    j++;
                }
                res += count;
                res += ch;
                ch = prev[j];
                count = 1;
            }
            prev = res;
            res = "";
            cout<<i+1<<" "<<res;
            */
        }

        return prev;
    }

解法二:遞歸

 string countAndSay(int n) {
      if(n==1) return "1";

      string prev = countAndSay(n-1);
      int left = 0;
      int right = 0;
      string res = "";

      while(left<prev.length()){
          while(prev[left]==prev[right]) right++;
          res += to_string(right-left)+ prev[left];
          left = right;
      }

      return res;
    }s

總結

起初我在思考這個問題的時候,並沒有想到遞歸,使用遞歸將會簡化代碼,更好的理解。

在使用迭代方法時,有以下一些注意事項:
1. 注意邊界值
- 遍歷次數從1到n-1: int i=1;i<n;i++
- 每個字符串遍歷: for(int j=1;j<=prev.length();j++) ;
- 對於字符串的prev[length]爲\0
2. 不需要單獨定義一個char存儲當前字符
3. 邏輯很簡單,simple is better.

發佈了43 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章