您的位置:首页 > 其它

在字符串中找出第一个只出现一次的字符

2016-04-21 09:09 120 查看
算法描述:

在字符串中找出第一个只出现一次的字符

算法实现:

/*************************************************************************
> File Name: FirstNotRepeatingChar.h
> Author: cyf
> Mail: XXX@qq.com
> Created Time: 2016年04月19日 星期二 16时00分43秒
************************************************************************/

#ifndef _FIRSTNOTREPEATINGCHAR_H
#define _FIRSTNOTREPEATINGCHAR_H
#include <stdio.h>
#include <stdlib.h>
#define HASHSIZE 256
char FirstNotRepeatingChar(char *pStr);

#endif


/*************************************************************************
> File Name: FirstNotRepeatingChar.c
> Author: cyf
> Mail: XXX@qq.com
> Created Time: 2016年04月19日 星期二 16时01分54秒
************************************************************************/

#include "FirstNotRepeatingChar.h"

char FirstNotRepeatingChar(char *pStr)
{

if (pStr == NULL)
{
return '\0';
}

unsigned int hashtable[HASHSIZE] = {0};

char *p = pStr;

while (*p != '\0')
{
hashtable[*(p++)]++;
}
p = pStr;

while (*p != '\0')
{
if (hashtable[*p] == 1)
{
return *p;
}
p++;
}

return '\0';
}
/*************************************************************************
> File Name: main.c
> Author: cyf
> Mail: XXX@qq.com
> Created Time: 2016年04月19日 星期二 16时10分01秒
************************************************************************/

#include "FirstNotRepeatingChar.h"

void Test(char *testname, char *string, char expected)
{
if (FirstNotRepeatingChar(string) == expected)
{
printf("test %s pass!\n", testname);
}
else
{
printf("test %s fail!\n", testname);
}

}
void Test1()
{
char string[] = "abaccdeff";
Test("Test1", string, 'b');
}

int main()
{
Test1();

return 0;

}
CC = gcc
CFLAGS = -g -O2 -Wall

%.o:%.c
$(CC) -o $@ -c $(CFLAGS) $<

main:main.o FirstNotRepeatingChar.o
$(CC) main.o FirstNotRepeatingChar.o -o main $(CFLAGS)

clean:
rm -rf *.o main
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: