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