O (n) time efficiency: Find the first occurrence character in the string, string

Source: Internet
Author: User

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 ;}


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.