Sword offer-Fifth chapter optimization of Time and space efficiency (the first occurrence of a tangent character in a string)

Source: Internet
Author: User

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)

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.