"Sword means offer" the first occurrence of a character position

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.