面试准备代码

1.原地压缩字符串

void num2str(char* str, char c, int num, int& n)
{
    *str++ = c; 
    if (num < 10)
    {
        *str++ = num + '0'; n = 2;
    }    
    else
    {
        vector<int> vtnum;
        while (num)
        {
            vtnum.push_back(num % 10);
            num = num / 10;
        }
        for (int i = vtnum.size() - 1; i >= 0; --i)
        {
            *str++ = vtnum[i] + '0';
        }
        n = vtnum.size() + 1;
    }
}

void CompressStr(char *str)
{
    if (NULL == str || str[0] == '\0' || str[1] == '\0') return;

    int num = 0, n;
    char *p1 = str, *p2 = str + 1, *p3 = str;

    while (*p2!='\0')
    {
        if (*p2 == *p1)
        {
            num = 1;
            while (p2)
            {
                if (*p2 == *p1)
                {
                    ++num;++p2;
                } else break;
            }
            num2str(p3, *p1, num, n);
            p3 += n; p1 = p2; ++p2;
            if (*p2 == '\0')
            {
                *(p3++) = *p1;break;
            }
        }
        else
        {
            *p3 = *p1;
            ++p1;++p2;++p3;
            if (*p2 == '\0')
            {
                *(p3++) = *p1;
            }
        }
    }
    *p3 = '\0';
    cout << str << endl;
}

 

posted @ 2015-09-05 19:25  从此寂静无声  阅读(195)  评论(0编辑  收藏  举报