Java Online Compiler
Example: Find First Non-Repeating Character in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Find First Non-Repeating Character import java.util.HashMap; import java.util.Map; import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static char findFirstNonRepeatingChar(String str) { // Step 1: Initialize a HashMap to store character counts. // Key: Character, Value: Count of occurrences Map<Character, Integer> charCounts = new HashMap<>(); // Step 2: First pass - Populate the HashMap with character frequencies. for (char c : str.toCharArray()) { charCounts.put(c, charCounts.getOrDefault(c, 0) + 1); } // Step 3: Second pass - Iterate through the string again to find the first character with a count of 1. for (char c : str.toCharArray()) { if (charCounts.get(c) == 1) { return c; // Found the first non-repeating character } } // Step 4: If no non-repeating character is found, return a sentinel value (e.g., '\0'). // Or, one could throw an exception or return a special character/string. return '\0'; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String inputString = scanner.nextLine(); char result = findFirstNonRepeatingChar(inputString); if (result != '\0') { System.out.println("The first non-repeating character is: '" + result + "'"); } else { System.out.println("No non-repeating character found in the string."); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS