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:
- Create a data structure to store the frequency of each character in the string.
- Iterate through the string to populate the frequency data structure.
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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 stringstr
as input and returns the first non-repeating character. - It uses a
HashMap
calledcharFrequency
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