leetcode Question 25: Count and Say


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.


Analysis:
The idea is simple, compare the current char in the string with the previous one, if they are the same, count +1, if not, print the previous char (count + char), set the new char and count, until the string ends.
Note that the the ascii code of '0' is 48, to convert the int to char we can use "char chr = i + '0';"



Source code:

class Solution {
public:

    string cas(string str){
        string str1;
        char ch=str[0];
        int chn=1;
        for(int i = 1; i<=str.size();i++){
            if (str[i]==ch){chn++;}
            else {
                char chr = chn+'0';
                str1 = str1+ chr;
                str1 = str1+ch;
                ch = str[i];
                chn=1;
            }
        }
        return str1;
    }
    string countAndSay(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (n==1) {return "1";}
        string str1 = "1";
        string strn;
        for (int i=1; i<n;i++){
            strn = cas(str1);
            str1 = strn;
        }
        return strn;
    }
};

4 comments:

  1. Hi Yu,

    If the count can be larger than 10?In this case ,'0' + chn may not work.

    Thanks,
    Di

    ReplyDelete
    Replies
    1. The count won't be large or equal than 10. There is a proof here:
      https://oj.leetcode.com/discuss/6762/how-to-proof-the-count-is-always-less-than-10

      Delete
  2. On line number 8, there is for loop which start from 1 and terminate if i>str.size(), For first time when string "1" enters in for loop and i =1 and i<="1".size() and it will go inside for loop and check if condition on line number 10, there would be string index exception. it will try to access str[1] which is not exits for string "1".
    Please explain me If i am wrong.

    ReplyDelete
  3. thanks, here is my solution https://www.tutorialcup.com/interview/string/count-and-say.htm

    ReplyDelete