Sword refers to offer-the first occurrence of a character-string and array

Source: Internet
Author: User

The algorithms used are all like bubble sort, directly select sort, insert sort

Every trip to deal with, this trip is of no practical significance

Variable J go from head to tail once Loop enumeration traversal scan

Title: The first character that appears only once

Title: Find the first character in a string that appears only once. If you enter "Abaccdeff", Output ' B '. Requires a time complexity of O (n).

The most intuitive idea is to scan each character in the string from the beginning. When a character is accessed, it is compared with each subsequent character typeface, and if no duplicate characters are found later, the character is the one that appears only once. If the string has n characters, each character may be compared to the typeface of the following O (n) characters, so the time complexity of the idea is O (n2), but it does not meet the requirements.

Second, the problem-solving ideas: space Change time

To solve this problem, we can define a hash table (the outer space) whose key value (key) is a character, and the value is the number of occurrences of that character.

We also need to scan the string two times from the beginning:

(1) When a string is scanned for the first time, each scan to a character adds 1 to the number of entries in the hash table. (Time efficiency O (n))

(2) on the second scan, the number of occurrences of that character can be obtained from the hash table each time a character is scanned. So the first character that appears only once is the output that meets the requirements. (Time efficiency O (n))

In this way, the total time complexity is still O (n), to meet the requirements of the topic, wipe a sweat, sigh: this * loaded really a bit of technology!

Finished B and started to implement this idea as code

Sword refers to offer-the first occurrence of a character-string and array

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.