Title: The first occurrence of a tangent character in a string
Idea: Use HashMap to store the corresponding char value and the number of occurrences of the char. Make a variable once to get the first character that appears only once.
Java code:
ImportJava.util.LinkedHashMap;//idea: Use HashMap to store the corresponding char value and the number of occurrences of the char. Make a variable once to get the first character that appears only once. Public classFirstnotrepeatingchar { PublicCharacter firstnotrepeating (String str) {if(str==NULL) return NULL; Char[] chars=Str.tochararray (); Linkedhashmap<Character,Integer> hashmap=NewLinkedhashmap<character,integer>(); for(Charitem:chars) { if(Hashmap.containskey (item)) Hashmap.put (item, Hashmap.get (item)+1); Elsehashmap.put (item,1); } for(CharKey:hashMap.keySet ()) { if(Hashmap.get (Key) ==1) returnkey; } return NULL; } Public Static voidMain (string[] args) {String str= "ABACCDEBFF"; Firstnotrepeatingchar Test=NewFirstnotrepeatingchar (); SYSTEM.OUT.PRINTLN (test.firstnotrepeating (str)); }}
Sword offer-Fifth chapter optimization of Time and space efficiency (the first occurrence of a tangent character in a string)