Classical algorithm Learning--the first character that appears only once

Source: Internet
Author: User

This is the same as the sword refers to the very classic question of the offer. The title is described as: Find the first occurrence of a character in a string.  If you enter "Abaccdeff", Output ' B '. At first, the simplest way to think of it is to compare every character you visit with each character, and if you don't find the same element, it's the first character that appears once.   This complexity is O (n^2). Obviously, this is not a high efficiency.

The general direction of the problem is a problem lookup algorithm, the common search algorithm for order lookup, binary lookup, hash lookup. The better fit for this problem is hash lookup. First we can create an array of 256 lengths, because there are 256 ASCII codes. We put the ASCII value of these characters to the index of the most array, that is, the key in the hash table, where the value in the array is the number of occurrences of that character. This way, by two traversal, you can find the character that conforms to test instructions (the first time to traverse the string, each access to a character based on the key value of the array value +1; the second is to iterate through the array and find the subscript ASCII that appears 1 for the first time). The degree of complexity is O (n). Complete code upload to https://github.com/chenyufeng1991/FirstAppearOnce.

The ASCII value of the letter as an array subscript, for    (int i = 0; i < mystring.length (); i++)    {        hashtable[mystring[i]]++;    }    for (int i = 0; i < mystring.length (); i++)    {        if (hashtable[mystring[i] = = 1)        {            cout << "first occurrence only one Characters of the second: "<< mystring[i" << Endl;            return 0;        }    }


Classical algorithm Learning--the first character that appears only once

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.