Saturday, April 13, 2013

Day 15, 38 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.
-------------------------------------------
Solution #1 recursive

class Solution {
public:
    string countAndSay(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (n == 1) {
            return "1";
        }
        string str = countAndSay(n-1);
        int count=1;
        char c = str[0];
        string re="";
        for (int i=1;i<str.length();i++) {
            
            if (c == str[i]) {
                count++;
            }else {
                re += count + '0';
                re += c;
                c = str[i];
                count = 1;
            }            
        }
        if (count == 1) {
            // last digit, single out
            re.push_back('1');
            re.push_back(c);
        }else {
            // multi 
            re += count + '0';
            re += str.back();
        }
        return re;
    }
};

Update on Sep-04-2014
Solution #2 iterative, watch out for string and character concatenation
class Solution {
public:
    string countAndSay(int n) {
        string str = "1";
        
        for (int i = 1; i < n; i++) {
            string temp = "";
            int count = 0;
            int slow = 0;
            for (int j = 0; j < str.length(); j++) {
                if (str[slow] == str[j]) {
                    count++;
                }else {
                    char ch = count + '0';
                    temp += ch;
                    temp += str[slow];
                    count = 1;
                    slow = j;
                }
            }
            char c = count + '0';
            temp += c;
            temp += str[slow];
            str = temp;
        }
        return str;
    }
};
Solution #3, refactored recursive
class Solution {
public:
    string countAndSay(int n) {
        if (n == 1) {
            return "1";
        }
        string str = countAndSay(n - 1);
        string temp = "";
        int slow = 0;
        int count = 0;
        for (int j = 0; j < str.length(); j++) {
                if (str[slow] == str[j]) {
                    count++;
                }else {
                    char ch = count + '0';
                    temp += ch;
                    temp += str[slow];
                    count = 1;
                    slow = j;
                }
        }
        char c = count + '0';
        temp += c;
        temp += str[slow];
        
        return temp; 
    }
};

No comments:

Post a Comment