Title: Find the first character in a string that appears only once. If you enter "Abaccdeff", Output ' B '.
Seeing this topic, our most intuitive idea is to scan the characters in this 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 following O (n) characters, so the time complexity of this idea is O (N2), the interviewer will not be satisfied with this idea, it will prompt us to continue thinking faster.
Since the topic is related to the number of occurrences of a character, we are not suspicious of counting the number of occurrences of each character in that string, and to achieve this we need a data container to hold the number of occurrences of each character. In this container, you can find the number of occurrences of a character based on its characters, which means that the function of this container is to map a character to a number. In a common data container, a hash table is the purpose.
To solve this problem, we can define that the hash table's 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. When a string is scanned for the first time, the number of occurrences in the hash table is added 1 per scan to a character. The next time a scan is made, the number of occurrences of that character can be obtained from the hash table for each character scanned. So the first character that appears only once is the output that meets the requirements.
Using Java code to implement our ideas:
/** * Find the first character in a string that appears only once. If input "Abaccdeff", then output ' B ' */package swordforoffer;import java.util.linkedhashmap;/** * @author Jinshuangqi * * August 9, 2015 * * public class E35firstnotrepeatingchar {public Character firstnotrepeating (String str) {if (str = = NULL) return null;char[] Strchar = Str.tochararray (); linkedhashmap<character,integer> hash = new linkedhashmap<character,integer> (); for (char Item:strChar) { if (Hash.containskey (item)) Hash.put (item, Hash.get (item) +1); Elsehash.put (item, 1);} for (char Key:hash.keySet ()) {if (Hash.get (key) = = 1) return key; return null;} public static void Main (string[] args) {String str = "ABACCDEBFF"; E35firstnotrepeatingchar test = new E35firstnotrepeatingchar (); SYSTEM.OUT.PRINTLN (test.firstnotrepeating (str));}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Sword Point of Offer (Java Edition): First occurrence of a character