[原创]顺序求出字符串中字符出现次数

有一字符串,全由小写字母组成,如“aaccbc”,要求顺序求出字符串中字符出现次数,如输出“a2c3b1”,求算法。

以下是本人第一次写的,时间复杂度为O(n^2)。

View Code
void func(const char *str)
{
    int i = 0;
    int temp = 0;
    int len = strlen(str);
    int A[26];
    while( i < 26 )
    {
        A[i]=0;
        i++;
    }
    while( temp < strlen(str) )
    {
        i = temp;
        if( A[str[i]-97] == 0 )
        {
            cout<<str[i];
            A[str[i]-97]++;
            while( ++i < strlen(str))
            {
                if ( A[str[i]-97] > 0 )
                {
                    A[str[i]-97]++;
                }
            }
            cout<<A[str[temp]-97];
        }
        temp++;
    }
}

然后又想到一个改进的想法,用大小为26的结构体数组来存,扫描一遍即可,时间复杂度为O(n),但是在顺序输出的时候稍微麻烦点儿。

View Code
typedef struct{
int count;
int appearSeq;
}S;
void func_upgrade(const char *str)
{    
    int i = 0;
    int j;
    int temp = 1; //记录字符出现的顺序
    int len = strlen(str);
    S s[26];
    while( i < 26 )
    {
        s[i].count = 0;
        s[i].appearSeq = 0;
        i++;
    }
    for( i = 0; i < len; i++ )
    {
        if( s[str[i]-97].count == 0 )
        {
            s[str[i]-97].appearSeq = temp;
            temp++;
        }
        s[str[i]-97].count++;
    }
    //按appearSeq顺序输出
    i=1;
    while( i < temp )
    {
        for ( j = 0; j < 26; j++ )
            if( s[j].appearSeq == i)
                cout<<char(j+97)<<s[j].count;
        i++;
    }    
}

不知谁有更好的想法,望不吝赐教。

posted @ 2012-04-13 20:02  XpowerLord  阅读(499)  评论(0编辑  收藏  举报