分享

第一个只出现一次的字符

 sky_feiyang 2014-07-04
#include<iostream>
#include<stdlib.h>
using namespace std;

//O(n^n)的时间复杂度
char FirstNotRepeatingChar2(char *pString)
{
    //如果是空指针,返回\0
    if(pString==NULL)
        return '\0';

    int len=strlen(pString);
    for(int i=0;i<len;i++)
    {
        int flag=0;//标识位,0表示这个字符只出现一次。
        for(int j=i+1;j<len;j++)
        {
            if(pString[i]==pString[j])
            {
                flag=1;//1表示在当前字符后面存在于该字符相同的字符。
            }
        }

        if(flag==0)
            return pString[i];
    }
    return '\0';
}

//O(n)的时间复杂度
char FirstNotRepeatingChar(char *pString)
{
    //如果是空指针,返回\0
    if(pString==NULL)
        return '\0';
    //定义hash表长度256,并创建哈希表
    const int len=256;
    int hashtable[len];

    for(int i=0;i<len;i++)
    {
        hashtable[i]=0;
    }

    char *pHashkey=pString;
    //第一遍遍历字符串,求出每个字符出现的次数
    while((*pHashkey)!='\0')
    {
        hashtable[*(pHashkey++)]++;
    }

    pHashkey=pString;
    //第二遍遍历字符串,求出第一个只出现一次的字符,每次都是按照字符串的顺序遍历
    while((*pHashkey)!='\0')
    {
        if(hashtable[*pHashkey]==1)
            return *pHashkey;
        pHashkey++;
    }
    return '\0';
}

void main()
{
    char *pString="abaccdeff";
    //cout<<pString<<endl;
    //cout<<pString[1]<<endl;
    cout<<sizeof(pString)<<endl;//4
    cout<<strlen(pString)<<endl;//9
    cout<<FirstNotRepeatingChar(pString)<<endl;
    cout<<FirstNotRepeatingChar2(pString)<<endl;
    system("pause");
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约