Find the First non-repeating Character in a given String

In this post, you will learn how to find the first non-repeating character in a given String using Java. To find the first non-repeating character in a given string, you can follow these steps:

  1. Create a data structure to store the frequency of each character in the string.
  2. Iterate through the string to populate the frequency data structure.
  3. Iterate through the string again to find the first character with a frequency of 1.

Java Program to Find the First Non-repeating Character

Here’s a Java program that implements the above approach:

package com.javacodepoint.string;

import java.util.HashMap;
import java.util.Map;
/*
 * Find the first non-repeating character in a given string
 */
public class FirstNonRepeatingCharacter {
	
	public static char findFirstNonRepeatingCharacter(String str) {
		Map<Character, Integer> charFrequency = new HashMap<>();

		// Populate the frequency map
		for (char c : str.toCharArray()) {
			charFrequency.put(c, charFrequency.getOrDefault(c, 0) + 1);
		}

		// Find the first non-repeating character
		for (char c : str.toCharArray()) {
			if (charFrequency.get(c) == 1) {
				return c;
			}
		}

		// If no non-repeating character is found, return a placeholder value
		return '\0';
	}

	public static void main(String[] args) {
		String input = "javacodepoint";
		char firstNonRepeating = findFirstNonRepeatingCharacter(input);

		if (firstNonRepeating != '\0') {
			System.out.println("First non-repeating character: " + firstNonRepeating);
		} else {
			System.out.println("No non-repeating character found.");
		}
	}
}

OUTPUT:

First non-repeating character: j

Explanation of the program:

  • The findFirstNonRepeatingCharacter method takes a string str as input and returns the first non-repeating character.
  • It uses a HashMap called charFrequency to store the frequency of each character in the string.
  • The first loop populates the frequency map by iterating through the characters of the string.
  • The second loop iterates through the string again and checks the frequency map to find the first character with a frequency of 1.

See also: Find the Maximum Occurring Character in a String

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *