String str = "zzzzzbbbccccddehhhhiii";
int[] countingArray = new int[128];
str.chars().forEach(value -> countingArray[value]++);
int nonRepeatingCharAsInt = 0;
for (int i = 0; i < countingArray.length; i++) {
if (countingArray[i] == 1) {
nonRepeatingCharAsInt = i;
break;
}
}
System.out.println("character = " + Character.valueOf((char) nonRepeatingCharAsInt));
Find first non-repeating character from a String
Carvia Tech | December 04, 2019 | 1 min read | 273 views
Approach
-
Use a LinkedHashmap to store frequency map of each character. LinkedHashmap keeps the items in the order of their insertion.
-
Iterate over all the input String one character at a time.
-
Filter only those entries that have frequency as 1.
-
Find the fist entry and get its key. This character has not been repeated from given input.
Traditional approach
using Java 8 Streams
import java.util.LinkedHashMap;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.util.function.Function.identity;
public class Utils {
private Optional<Character> findFirstNonRepeatingLetter(String s) {
final Optional<Character> optionalCharacter = s.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() == 1L)
.map(entry -> entry.getKey())
.findFirst();
return optionalCharacter;
}
}
Top articles in this category:
- Find longest non-repeating substring from a given string in Java
- Reverse a string using recursion in Java
- SDET Java Coding Challenges
- Check if the given string is palindrome
- 50 SDET Java Interview Questions & Answers
- Palindrome checker in Java
- Rest Assured API Testing Interview Questions
Find more on this topic:
Subscribe to Interview Questions
Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..
Similar Posts
- Reverse position of words in a string using recursion
- REST Assured with plain/text response body
- Get distinct words from a given file in Java
- SDET Java Coding Challenges
- REST Assured vs Apache HttpClient and RestTemplate
- Java 11 HttpClient with Basic Authentication
- HTTP GET request with Java 11 HttpClient - Kotlin
- HTTP Head request using Java 11 HttpClient - Kotlin
- Using Java 11 HttpClient with Kotlin Coroutines
- Migrating Spring Boot tests from Junit 4 to Junit 5