4 Ways to Find the First Non-Repeated Character in a String in Java

In this article, we will explore four different approaches to finding the first non-repeated character in a string using Java. Each method offers a unique way to solve the problem, ranging from simple loops to more advanced functional programming techniques.

Problem Statement

Given a string, find the first character that does not repeat. If no such character exists, return a special indicator (such as null or a specific character).

Example:

  • Input: "swiss"
  • Output: 'w' (The first non-repeated character is 'w')

Approach 1: Loop and Break Solution

This is the most straightforward approach, where we use two nested loops. The outer loop picks characters one by one, and the inner loop checks if the character is repeated. Once the first non-repeated character is found, we break out of the loop.

Java Code

public class FirstNonRepeatedCharacter {

    public static void main(String[] args) {
        String str = "swiss";
        char result = findFirstNonRepeatedChar(str);
        System.out.println("First non-repeated character is: " + result);
    }

    public static char findFirstNonRepeatedChar(String str) {
        for (int i = 0; i < str.length(); i++) {
            boolean isRepeated = false;
            for (int j = 0; j < str.length(); j++) {
                if (i != j && str.charAt(i) == str.charAt(j)) {
                    isRepeated = true;
                    break;
                }
            }
            if (!isRepeated) {
                return str.charAt(i);
            }
        }
        return '\0'; // or another indicator for no non-repeated character
    }
}

Output

First non-repeated character is: w

Approach 2: 256 ASCII Codes Solution

This approach assumes that the string contains only ASCII characters. We use an array of size 256 (the number of ASCII characters) to count the frequency of each character. In the second pass, we check the string again and find the first character with a count of 1.

Java Code

public class FirstNonRepeatedCharacterASCII {

    public static void main(String[] args) {
        String str = "swiss";
        char result = findFirstNonRepeatedChar(str);
        System.out.println("First non-repeated character is: " + result);
    }

    public static char findFirstNonRepeatedChar(String str) {
        int[] charCount = new int[256]; // Assuming ASCII characters

        // Populate the frequency array
        for (int i = 0; i < str.length(); i++) {
            charCount[str.charAt(i)]++;
        }

        // Find the first non-repeated character
        for (int i = 0; i < str.length(); i++) {
            if (charCount[str.charAt(i)] == 1) {
                return str.charAt(i);
            }
        }
        return '\0'; // or another indicator for no non-repeated character
    }
}

Output

First non-repeated character is: w

Approach 3: LinkedHashMap Based Solution

Using a LinkedHashMap, we can maintain the insertion order of characters while counting their occurrences. This allows us to find the first non-repeated character efficiently by iterating over the map.

Java Code

import java.util.LinkedHashMap;
import java.util.Map;

public class FirstNonRepeatedCharacterLinkedHashMap {

    public static void main(String[] args) {
        String str = "swiss";
        char result = findFirstNonRepeatedChar(str);
        System.out.println("First non-repeated character is: " + result);
    }

    public static char findFirstNonRepeatedChar(String str) {
        Map<Character, Integer> charCountMap = new LinkedHashMap<>();

        // Populate the LinkedHashMap with character counts
        for (char ch : str.toCharArray()) {
            charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
        }

        // Find the first non-repeated character
        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            if (entry.getValue() == 1) {
                return entry.getKey();
            }
        }
        return '\0'; // or another indicator for no non-repeated character
    }
}

Output

First non-repeated character is: w

Approach 4: Java 8 Functional-Style Solution

This approach leverages Java 8's Stream API to create a more functional and concise solution. We use Collectors.groupingBy to count the characters and filter to find the first non-repeated character.

Java Code

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FirstNonRepeatedCharacterJava8 {

    public static void main(String[] args) {
        String str = "swiss";
        Character result = findFirstNonRepeatedChar(str);
        System.out.println("First non-repeated character is: " + result);
    }

    public static Character findFirstNonRepeatedChar(String str) {
        Map<Character, Long> charCountMap = str.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));

        return charCountMap.entrySet().stream()
                .filter(entry -> entry.getValue() == 1)
                .map(Map.Entry::getKey)
                .findFirst()
                .orElse(null); // or another indicator for no non-repeated character
    }
}

Output

First non-repeated character is: w

Conclusion

These four approaches provide different ways to find the first non-repeated character in a string using Java. The loop-and-break solution is straightforward, the 256 ASCII codes solution is efficient for fixed character sets, the LinkedHashMap solution maintains insertion order, and the Java 8 functional-style solution is concise and leverages modern Java features. Each approach has its own advantages, and the choice of method may depend on the specific requirements and constraints of your project.

Comments