The first character position that appears only once

Source: Internet
Author: User

Title Description: In a string (1<= string length <=10000, all composed of letters) to find the first occurrence of a character position.
* If the string is empty, return-1. Position index starting from 0

Solution One:

 Public intFirstnotrepeatingchar (String str) {if(str==NULL)return-1; intAddress=0; Char[] ch = str.tochararray ();//save an array of each character//Linkedhashmap saves the order in which records are inserted, and when traversing linkedhashmap with iterator, the first records must be inserted first. linkedhashmap<character,integer> hash =NewLinkedhashmap<character,integer>();  for(inti=0;i<ch.length;i++){            if(Hash.containskey (Ch[i])) {hash.put (Ch[i], Hash.get (ch[i))+1);//Add 1 to the number of occurrences of item;}Else{hash.put (ch[i],1); }                }            /*For (char Key:hash.keySet ()) {if (Hash.get (key) ==1) {return key;//here is the character that returns the first occurrence only once, then his position? }        }*/          for(inti=0;i<ch.length;i++){                if(Hash.get (Ch[i]) ==1)returni; }            return-1; }

Solution Two: No memory consumption

 Public intFirstnotrepeatingchar (String str) {//when the letter case of the string is consistent, it is either all uppercase or all lowercase.         if(str.length () = = 0) {            return-1; }        Charc = ' A ';//initialize C, starting with a,        if(Str.charat (0) >= ' a ') {C= ' a ';//If the first letter is lowercase, start with a,        }        int[] counts =New int[26];//the difference between characters will not be greater than         for(inti = 0; I < str.length (); i++) {Counts[str.charat (i)-c]++;//represents        }         for(inti = 0; I < str.length (); i++) {            if(Counts[str.charat (i)-c] = = 1){                returni; }        }        return-1; }

The first character position 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.