Package com.abuge;
/** * Face Test 35: The first occurrence of the character * title: In the string to find the first occurrence of only one character, such as the input "Abaccdeff", then output ' B '/import java.util.HashMap;
public class Getfirstoncechar {public static char getfirstonce (String str) {if (str = null) return ' 0 ';
hashmap<string, integer> HashMap = new hashmap<string, integer> ();
int len = Str.length ();
Iterates through the string, counting the number of occurrences of each character in the string for (int i = 0; i < len; i++) {String tmpstr = "" + Str.charat (i);
if (Hashmap.containskey (TMPSTR)) {int value = Hashmap.get (TMPSTR);
value++;
Hashmap.remove (TMPSTR);
Hashmap.put (tmpstr, value);
}else {hashmap.put (tmpstr, 1);
}//Iterate through the string again to find the character for (int i = 0; i < len; i++) {String tmpstr = "" + Str.charat (i);
int value = Hashmap.get (TMPSTR);
if (value = = 1) {System.out.println (Str.charat (i));
return Str.charat (i);
} return ' 0 ';
///Custom hash table public static char getfirstonce_2 (String str) {if (str = null) {return ' 0 ';
//Only consider ASCII code, so there are 256 characters int[] hashTable = new int[256];
int len = Str.length ();
Traversal string for (int i = 0; i < len; i++) {char c = str.charat (i);
hashtable[c]++;
///Traversal string find the first occurrence of the character for (int i = 0; i < len; i++) {char c = str.charat (i);
if (hashtable[c] = = 1) {System.out.println (c);
return C;
} return ' 0 ';
public static void Main (string[] args) {System.out.println ("single character:");
Getfirstonce ("a");
Getfirstonce_2 ("a");
System.out.println ("No single character exists:");
Getfirstonce_2 ("Bbccddee");
System.out.println ("All is a single string:");
Getfirstonce ("Bacde");
Getfirstonce_2 ("Bacde");
System.out.println ("There is a character normal string that appears once:");
Getfirstonce ("Abaccdeff");
Getfirstonce_2 ("Abaccdeff");
SYSTEM.OUT.PRINTLN ("null:");
Getfirstonce (NULL);
Getfirstonce_2 (NULL);
}
}