找出字符串中第一次出现一次的字符
2011-01-03 17:33
183 查看
#include<stdio.h> #include<string.h> #include<malloc.h> char find_once_char(char * str) { int len=strlen(str); //char A[len]={0}; //int num[len]={0}; 这样 的 初始化是 不对 的 ,一个 运行 ,一个 编役 char *A=(char *)malloc(len); if(A==NULL) return -1; int *num=(int *)malloc(sizeof(int)*len);//how to release? if(num==NULL) return -1; char *p=str; int number=0; int i=0; while(*p!='/0') { for(i=0;i<number;i++) { if(A[i]==*p) { num[i]++; break; } } //if(i>=number) if(i>=number) { num[i]=1; A[i]=*p; number++; } if(num[0]==0) { num[0]=1; A[0]=*p; number++; } p++; } for(i=0;i<number;i++) if(num[i]==1) { return A[i]; } return -1; } int main(int argc,char *args[]) { char string[]="aaddefghedfghbecfagdef"; char word=find_once_char(string); /*if(word!=-1) { //free(A); //free(num);//num had alread released }*/ printf("%c/n",word); return 0; }
这段代码未释放内存,所以还是用数组,数组大小为char字符的大小
再贴一段代码,比较比较
#include <stdio.h> #include <limits.h> char* find_first_once(char* s) { int map[UCHAR_MAX] = {0}; char *tmp = s; while (*tmp) ++map[*tmp++]; while (*s) if (1 == map[*s]) return s; else s++; return NULL; } int main(int argc, char* argv[]) { char *s = "aaddefghedfghbecfagdef"; char *p = find_first_once(s); if (p) { printf("%c:%d/n", *p, p-s); } else { printf("none!/n"); } return 0; }
通过map数组对应,直接对map[*temp]++,避免了循环比较相等再加加的操作
#include <limits.h> const char* find_first_once(const char* s) { int map[UCHAR_MAX] = {0}; const char *ptr = s; while (*ptr) { map[*ptr]++; ptr++; } ptr = NULL; while (*s) { if (1 == map[*s]) { ptr = s; break; } else { s++; } } return ptr; } int main(int argc, char* argv[]) { const char *s = "abcdabce"; const char *p = find_first_once(s); if (p) { printf("%c:%d/n", *p, p-s); } else { printf("none!/n"); } return 0; }
代码增加了const对变量的限定,return语句减少了,大括号的运用
相关文章推荐
- 如何找出一个字符串中第一次且只出现一次的字符
- 华为oj_找出字符串中第一个只出现一次的字符
- LeetCode:找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- C++求字符串第一次只出现一次的字符
- O(n)时间效率寻找字符串中第一次出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 字符串查找:(第一次)&&(只出现一次的字符)
- 剑指-在字符串中找出第一个只出现一次的字符
- 只允许遍历一遍字符串,找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 给出一个字符串,找出其中只出现一次且位置最靠前的那个字符
- 找出字符串中第一个只出现一次的字符
- 在一个字符串中找出第一次重复出现的字符
- 【C语言【面试题】【笔试题】题目:在字符串中找出第一个只出现一次的字符。
- 只允许遍历一遍字符串,找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出一个字符串中,第一个只出现一次的字符
- 【笔试题】C语言:在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出&#39;b&#39;。
- 华为机试——找出字符串中第一个只出现一次的字符