O (n) Time efficiency find the first occurrence of a character in a string

Source: Internet
Author: User

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

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.