zoukankan      html  css  js  c++  java
  • [原创]顺序求出字符串中字符出现次数

    有一字符串,全由小写字母组成,如“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++;
        }    
    }

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

    如原创文章,转载请注明:转自http://www.cnblogs.com/xpowerlord/
  • 相关阅读:
    软件工程第四次作业
    软件工程第三次作业
    图片
    软件工程第二次作业
    软件工程第一次作业
    我的大学生活-3-35-任延勇
    我的未来只有我知道
    cpu占用率高排查知识点
    LeetCode字符串题目
    hashmap
  • 原文地址:https://www.cnblogs.com/xpowerlord/p/2446286.html
Copyright © 2011-2022 走看看