Find the first non-repeated character in a String
This is a common question in coding interviews.
To find the first non-repeated character in a String, we can use multiple solutions.
Using LinkedHashMap
In questions where we need to count the number of times an element appears in a list or string, it is always best to use a HashMap. But, since the HashMap does not preserve the insertion order, and we need it here, we need to use a LinkedHashMap that does preserve the insertion order.
public class DevPrimer {
public static void main(String[] args) {
System.out.println(firstNonRepeatedCharacter("agcdefgchija"));
}
private static Character firstNonRepeatedCharacter(String str) {
Map<Character, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < str.length(); i++) {
if (map.containsKey(str.charAt(i))) {
map.put(str.charAt(i), map.get(str.charAt(i)) + 1);
} else {
map.put(str.charAt(i), 1);
}
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return null;
}
} Output: d
Finds the first non-repeated character in a String in one pass
Here, we are storing repeated and non-repeated characters separately:
public class DevPrimer {
public static void main(String[] args) {
System.out.println(firstNonRepeatedCharacter("agcdefgchija"));
}
private static Character firstNonRepeatedCharacter(String str) {
Set<Character> repeating = new HashSet<>();
List<Character> nonRepeating = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
if (repeating.contains(str.charAt(i))) {
continue;
}
if (nonRepeating.contains(str.charAt(i))) {
nonRepeating.remove((Character) str.charAt(i));
repeating.add(str.charAt(i));
} else {
nonRepeating.add(str.charAt(i));
}
}
return nonRepeating.get(0);
}
} Output: d
This is a classical time vs space trade-off.
No comments:
Post a Comment