<leetcode系列> 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.

题意如下,:
每一次数前一个数, 如:
第一个数是1, 那么下一个数就是:1个1, 即11;
第二个数是11,那么下一个数就是:2个1, 即21;
第三个数是21,那么下一个数就是:1个2,1个1,即1211;
第四个数是1211,那么下一个数就是:1个1,1个2,2个1, 即111221;
… …
以此类推, 如果遇到111, 就是3个1, 即31.

题目链接: https://leetcode.com/problems/count-and-say/

由于很少使用标准库中的各种数据结果,如vector, map等,对于string这种类型,其中的各种成员函数都要先百度,才只有有什么可以调用,不同库中的string又有不小的差异.故我选用的是C语言.代码如下:

void fillBuf(char** buf, const char curChar, char* lastChar, int* count) {
    if (('\0' == *lastChar) || (curChar == *lastChar)) {
        ++(*count);
    } else {
        sprintf(*buf, "%d", *count);
        ++(*buf);
        // *buf++ = curChar;
        **buf = *lastChar;
        ++(*buf);
        *count = 1;
    }

    *lastChar = curChar;
}

void fillBuf1(char** buf, char lastChar, int count) {
    sprintf(*buf, "%d", count);
    ++(*buf);
    // *buf++ = curChar;
    **buf = lastChar;
    ++(*buf);
}

char* countAndSayNext(const char* cur, int size, int* retSize) {
    if ((NULL == cur) || (0 >= size) || (NULL == retSize)) {
        return NULL;
    }

    const int MAX_SIZE = size * 2; // 下一个数的长度, 肯定不会大于上一个数的两倍(极端情况, 全是1)
    char* pRet = (char*) malloc(MAX_SIZE * sizeof(char));
    memset(pRet, '\0', MAX_SIZE * sizeof(char));

    char* offset = pRet;
    int count = 0;
    char lastChar = '\0';
    for (int i = 0; i < size; ++i) {
        // 计数相同字符或写入已记录字符
        fillBuf(&offset, cur[i], &lastChar, &count);
    }
    // 填充最后一个记录的字符
    fillBuf1(&offset, lastChar, count);

    *retSize = offset - pRet;
    char* ret = (char*) malloc((*retSize + 1) * sizeof(char));
    memset(ret, '\0', (*retSize + 1) * sizeof(char));
    memcpy(ret, pRet, *retSize);

    free(pRet);
    pRet = NULL;
    return ret;
}

char* countAndSay(int n) {
    if (0 >= n) {
        return NULL;
    }

    // char fristNum = '1';
    // char* pCur  = &fristNum;
    int size = 1;
    // size + 1: 提供'\0', 否则显示会出现错误
    char* pCur  = (char*) malloc((size + 1) * sizeof(char));
    char* pNext = NULL;
    memset(pCur, '\0', (size + 1) * sizeof(char));
    *pCur = '1';

    for (int i = 1; i < n; ++i) {
        /*if (NULL != pNext) {
            free(pNext);
            pNext = NULL;
        }*/
        // 在countAndSayNext中申请了内存,并未被释放,故需要在此处释放
        pNext = countAndSayNext(pCur, size, &size);
        free(pCur);
        pCur  = pNext;
    }

    return pCur;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值