字符串长度:n
字符可能个数:m(剑指OFFER中m为256)
剑指OFFER P187中的方式平均约循环次数为:1*n ~ 2*n(依赖于出现一次的字符所处的位置),耗时也跟着浮动:1*t~2*t
原本的思路为
1、读取每一个字符,对每个字符进行计数(循环n次)
2、再次读取每一个字符,直到遇到计数为1的字符为止
优化第二点:采用一个数组记录下每个字符第一次出现的位置,计数大于1的设为最大值(字符串最大长度),对其进行排序(mlogm),第一个就是第一次出现的。
优化后的好处一是时间稳定在1.5*t,二是不需要再次读取输入字符串,节省内存。(注:下面的代码并未完善,合适的方式应该是读取一个字符便处理一次,因而额外的空间为3*m*24;旧的方式需要的额外空间为1*m*24+n.)
另外,0x21~0x7f这个范围设定是360笔试中的^_^
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
//0x7F - 0x21 = 94
// 0,1,2... 94 分别记录 0x21,0x22,...,0x7F
#define MAX_STRING_LENGTH 100000
#define MAX_CHAR_NUMBER 95
typedef struct __CountCharInfo {
char orgidx;
long long count;
long long seq;
} CountCharInfo;
int ccicomp(const void*a,const void*b)
{
CountCharInfo *a1 = (CountCharInfo*)a;
CountCharInfo *b1 = (CountCharInfo*)b;
return (a1->seq - b1->seq);
}
void cciinit(CountCharInfo *cci, int n) {
for (int i = 0; i < n; i++) {
cci[i].orgidx= i;
cci[i].count = 0;
cci[i].seq = MAX_STRING_LENGTH;
}
}
char GetOnetimeChar(char s[]) {
CountCharInfo cci[MAX_CHAR_NUMBER];
cciinit(cci, MAX_CHAR_NUMBER);
long long len = strlen(s);
long long i;
char j;
bool exist = 0;
for (i = 0; i < len; i++) {
cci[s[i] - 0x21].count++;
if (cci[s[i] - 0x21].seq == MAX_STRING_LENGTH) {
cci[s[i] - 0x21].seq = i;
}
}
for (j = 0; j < MAX_CHAR_NUMBER; j++) {
if (cci[j].count != 1) {
cci[j].seq = MAX_STRING_LENGTH;
} else {
exist = 1;
}
}
//cci.seq排序
if (exist) {
qsort(cci, MAX_CHAR_NUMBER, sizeof(cci[0]), ccicomp);
} else {
return 0;
}
return (0x21 + cci[0].orgidx);
}
char GetOnetimeCharOld(char s[]) {
CountCharInfo cci[MAX_CHAR_NUMBER];
cciinit(cci, MAX_CHAR_NUMBER);
long long len = strlen(s);
long long i;
bool exist = 0;
for (i = 0; i < len; i++) {
cci[s[i] - 0x21].count++;
}
for (i = 0; i < len; i++) {
if (cci[s[i] - 0x21].count == 1) {
return (0x21 + cci[s[i] - 0x21].orgidx);
}
}
return 0;
}
void GenerateString(char *str, int len) {
srand(time(NULL));
for (long long i = 0; i < len; i++) {
str[i] = rand()%(0x7E - 0x21) + 0x21;
}
str[len-2] = 0x7F;
str[len-1] = '\0';
}
int main() {
char str[MAX_STRING_LENGTH] = "";
char out;
int i, n;
char strTest[MAX_STRING_LENGTH] = "";
clock_t start, end;
GenerateString(strTest, MAX_STRING_LENGTH);
start = clock();
for(i = 0; i < 100; i++) {
out = GetOnetimeChar(strTest);
}
end = clock();
printf("\t----%d-%f----\n", out, (double)(start-end)/CLOCKS_PER_SEC);
start = clock();
for(i = 0; i < 100; i++) {
out = GetOnetimeCharOld(strTest);
}
end = clock();
printf("\t----%d-%f----\n", out, (double)(start-end)/CLOCKS_PER_SEC);
/*
scanf("%d\n", &n);
for (i = 0; i < n; i++) {
memset(str, 0, 1000000);
scanf("%s", str);
out = GetOnetimeChar(str);
printf("%c\n", out);
}
*/
getchar();
}