O (n) time efficiency: Find the first occurrence character in the string, string
Idea: we use simple hash ing to solve this problem.
Create an array, use the subscript of the array to correspond to the value of each character, and then scan the string to add 1 to the position of the array corresponding to the value of each character, finally, scan the array in the character sequence in the string. When the first character is entered, the corresponding character can be found.
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}; // create a simple hash ing subscript representing 256 characters const char * p = str; while (* p! = '\ 0') {ar [* p ++] ++;} p = str; while (* p! = '\ 0') {if (ar [* p] = 1) {return * p;} + p;} throw std: exception ();} int main () {const char * p = "abaccdeff"; cout <findch (p, strlen (p) <endl; const char * q = ""; 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 = "haabcd"; cout <findch (t, strlen (t) <endl; return 0 ;}