Thursday, April 24, 2014

LeetCode: 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.


Just follow the rules and generating one by one

C++ Code:

/*
 * func: count_and_say
 * goal: given an integer n, generate the nth count-and-say sequence
 * @param n:
 * return: string of the sequence
 */

string count_and_say(int n){
    assert(n > 0);
    string result = "1";
    int counter = 1;
    
    while(counter < n){
        size_t index = 0;
        string iter_result = "";
        int iter_counter = 1;
        while(index < result.length()-1){
            if(result[index+1] == result[index]){
                ++index;
                ++iter_counter;
            }else{
                iter_result += iter_counter + '0';
                iter_result += result[index];
                ++index;
                iter_counter = 1;
            }
        }
        
        //count the last digit
        iter_result += iter_counter + '0';
        iter_result += result[index];
        
        ++counter;
        result = iter_result;
    }
    
    return result;
}

Python Code:

# func: given an integer n, generate nth count-and-say sequence
# @param n: input integer n
# @return: the nth sequence as a string
def count_and_say(n):
    assert n > 0

    result = '1'
    counter = 1
    while counter < n:
        digit_counter = 1
        i = 0
        inner_result = ''
        while i < len(result)-1:
            if result[i] == result[i+1]:
                digit_counter += 1
                i += 1
            else:
                inner_result += str(digit_counter) + result[i]
                i += 1
                digit_counter = 1

        inner_result += str(digit_counter) + result[i]
        result = inner_result
        counter += 1

    return result

No comments:

Post a Comment