Problem description
The position of the first occurrence of a character in a string (1<= string length <=10000, all composed of letters) is found. If the string is empty, return-1. The position index starts at 0.
Example:
Input: SABCDSDF
Output: 1
Algorithm description
Defines an integer array of 52 elements acount, initialized to 0, each letter (case) corresponding to one, recording the number of letters appearing;
Defines an integer array of 52 elements apos, initialized to-1, each letter (case) corresponds to one, recording the position of the first occurrence of the letter;
Each time traversing one to the letter, the acount array corresponding to the letter plus 1, to determine whether the current acount array of the letter count is 1, is in the APOs to record the position of the letter, if it is not 1, the position is set to-1.
Finally traverse APOs, not 1 and the smallest one is the position of the first character that appears once.
Run time O (n)
Code implementation
class solution { Public:intFirstnotrepeatingchar (StringStr) {//empty string return-1 if(Str=="")return-1;//First 26 elements represent lowercase letters, and the last 26 elements represent uppercase letters intacount[ the], apos[ the]; for(inti =0; I < the; i++) {Acount[i] =0; Apos[i] =-1; }//Start traversal for(inti =0; I <Str. Length (); i++) {intpos =0;if(Str[I] >=' A '&&Str[I] <=' Z ') {pos =Str[I]-' A '; }Else{pos =Str[I]-' A '+ -; } Acount[pos] + =1;if(Acount[pos] = =1) {Apos[pos] = i; }Else{Apos[pos] =-1; } }///Last Judgment apos array intresult =-1;//If not, return-1 for(inti =0; I < the; i++) {if(Apos[i]! =-1) {if(Result = =-1) result = Apos[i];ElseResult = result < Apos[i]? Result:apos[i]; } }returnResult }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Sword means offer" the first occurrence of a character position