Java Program to Find the First Non-repeated Character in a String

Introduction

In this guide, we will develop a Java program to find the first non-repeated character in a string. Identifying the first character that does not repeat in a sequence is a common task in programming, especially in text processing and data analysis. The program will efficiently scan the string and determine the first character that appears only once, providing a useful solution to this problem.

Problem Statement

Given a string, the task is to find the first character that does not repeat in the entire string. If no such character exists, the program should indicate that no non-repeated character was found.

Example 1:

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

Example 2:

  • Input: "programming"
  • Output: 'p' (The first non-repeated character is 'p')

Example 3:

  • Input: "aabbcc"
  • Output: No non-repeated character found.

Solution Steps

  1. Initialize a Map: Use a LinkedHashMap to store each character of the string along with its occurrence count. The LinkedHashMap maintains the order of insertion, which helps in identifying the first non-repeated character.

  2. Iterate Through the String: Convert the string into a character array and populate the map with character counts as you iterate through the array.

  3. Find the First Non-Repeated Character: Traverse the entries of the LinkedHashMap. The first entry with a count of 1 is the first non-repeated character.

  4. Return the Result: If a non-repeated character is found, return it. Otherwise, return a special character ('\0') or a specific message indicating that no non-repeated character was found.

Java Program

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

/**
 * Java Program to Find the First Non-Repeated Character in a String
 * Author: https://www.javaguides.net/
 */
public class FirstNonRepeatedCharacter {

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

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

        // Find the first non-repeated character
        for (Map.Entry<Character, Integer> entry : characterCountMap.entrySet()) {
            if (entry.getValue() == 1) {
                return entry.getKey();
            }
        }

        // If no non-repeated character is found, return a null character
        return '\0';
    }

    public static void main(String[] args) {
        String input = "swiss";
        char result = findFirstNonRepeatedCharacter(input);

        if (result != '\0') {
            System.out.println("The first non-repeated character is: " + result);
        } else {
            System.out.println("No non-repeated character found.");
        }
    }
}

Output

For the input "swiss", the output will be:

The first non-repeated character is: w

Step by Step Explanation

  1. Input String: The input string provided is "swiss".

  2. Map Initialization: A LinkedHashMap is used to store the characters as keys and their occurrence counts as values.

  3. Counting Characters:

    • The first 's' is encountered, so it is added to the map with a count of 1.
    • The character 'w' is added next with a count of 1.
    • The character 'i' is added with a count of 1.
    • The subsequent 's' characters increase the count of 's' in the map to 2 and then 3.
  4. Finding the First Non-Repeated Character: The program iterates through the LinkedHashMap entries and finds that 'w' is the first character with a count of 1.

  5. Output: The program prints "The first non-repeated character is: w".

Best Practices

  • Use of LinkedHashMap: The LinkedHashMap is ideal for this problem as it maintains the order of insertion, ensuring that the first unique character is identified correctly.
  • Efficient Iteration: The string is scanned twice—once to count occurrences and once to find the first non-repeated character, ensuring optimal performance.
  • Edge Case Handling: The program returns a special character ('\0') or a clear message when no non-repeated character is found, making it robust against various inputs.

Conclusion

This Java program provides a clear and efficient solution to finding the first non-repeated character in a string. By using a LinkedHashMap, the program ensures that characters are processed in the order they appear, making it easy to identify the first unique character. This method is efficient and handles edge cases effectively, making it a reliable solution for string processing tasks.

Related Java String Programs with Output

Comments