Idea: We use simple hash map to solve this problem .
Set up an array, with the array's subscript corresponding to each character's value, and then scan the string, give each character the value of the array of the number of positions plus 1, and then scan the array, encountered the first 1 o'clock, you can find the corresponding character
The implementation code is as follows:
#include <iostream> #include <cassert>using namespace Std;char findch (const char *str, int len) {assert (str! = NULL); int ar[256] = {0};//establishes a simple hash map subscript that represents a 256-character const char *p = Str;while (*p! = ') ' {ar[*p++]++;} int i = 0;for (i; i<256; ++i) {if (ar[i] = = 1) {break;}} if (i! =) {return i;} Else{throw std::exception ();}} int main () {const char *p = "Abaccdeff"; Cout<<findch (P, strlen (p)) <<endl;const char *q = "a";cout<< FINDCH (q, strlen (p)) <<endl;//const char *r = "AAAAAAAAA";//cout<<findch (R, strlen (p)) <<endl;// const char *s = "";//cout<<findch (S, strlen (p)) <<endl;const char *t = "AAAAAAAAAAAABCDEFG";cout<< FINDCH (T, strlen (t)) <<endl;return 0;}
O (n) Time efficiency find the first occurrence of a character in a string