First unique character in a string
Question: Given a string, find the unique character in the first string. For example, "cisco" should be I, and "cat" should be c.
The first method is to use LinkedHashMap to keep the data order, repeat the string, count the characters, and then find the first character with a quantity of 1.
The second method is to use a HashSet to store repeated characters, and then use an arraylist to store only the characters that appear once.
The third method is to use HashMap to store data and count, and then go through the string to check whether the count for each character is 1.
Code:
Import java. io. IOException; import java. util. arrayList; import java. util. hashMap; import java. util. hashSet; import java. util. linkedHashMap; import java. util. list; import java. util. map; import java. util. map. entry; import java. util. set; public class FirstUniqueCharacter {// method 1 public static char getFirstNonRepeatedChar (String str) {Map
Counts = new LinkedHashMap <> (str. length (); for (char c: str. toCharArray () {counts. put (c, counts. containsKey (c )? Counts. get (c) + 1: 1);} for (Entry
Entry: counts. entrySet () {if (entry. getValue () = 1) {return entry. getKey () ;}} throw new RuntimeException ("didn't find any non repeated Character") ;}// method 2 public static char firstNonRepeatingChar (String word) {Set
Repeating = new HashSet <> (); List
NonRepeating = new ArrayList <> (); for (int I = 0; I <word. length (); I ++) {char letter = word. charAt (I); if (repeating. contains (letter) {continue;} if (nonRepeating. contains (letter) {nonRepeating. remove (Character) letter); repeating. add (letter);} else {nonRepeating. add (letter) ;}return nonRepeating. get (0);} // method 3 public static char firstNonRepeatedCharacter (String word) {HashMap
Scoreboard = new HashMap <> (); // build table [char-> count] for (int I = 0; I <word. length (); I ++) {char c = word. charAt (I); if (scoreboard. containsKey (c) {scoreboard. put (c, scoreboard. get (c) + 1);} else {scoreboard. put (c, 1) ;}}// since HashMap doesn't maintain order, going through string againfor (int I = 0; I <word. length (); I ++) {char c = word. charAt (I); if (scoreboard. get (c) = 1) {return c ;}} throw new RuntimeException ("Undefined behaviour ");}}
Reference: http://javarevisited.blogspot.com/2014/03/3-ways-to-find-first-non-repeated-character-String-programming-problem.html