问题描述:
在字符串中找到第一个只出现一次的字符。
例如:
输入"abaccdeff",则输出'b'。
实现代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include<String.h>
char find(char *ch,int n){
int hashTable[256]={
0
};
int i;
for(i=0;i<n;i++){
int positoin= ch[i]%256;
hashTable[positoin]++;
}
for(i=0;i<256;i++){
if(hashTable[i]==1){
return i;
}
}
return ' ';
}
int main(int argc, char *argv[])
{
char ch[]="qazwsxqz";
int n = strlen(ch);
char c = find(ch,n);
printf("%c\n",c);
return 0;
}上面算法的时间复杂度为O(n)。
参考资料:
剑指offer
备注:
转载请注明出处:http://blog.youkuaiyun.com/wsyw126/article/details/51383831
作者:WSYW126
本文介绍了一种高效的算法,用于从字符串中找出第一个仅出现一次的字符。通过使用哈希表记录每个字符出现次数,并两次遍历字符串,实现了O(n)的时间复杂度。
1195

被折叠的 条评论
为什么被折叠?



