Java Online Compiler
Example: First Non-Repeating Character using Frequency Array in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// First Non-Repeating Character using Frequency Array import java.util.Optional; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { String input1 = "swiss"; String input2 = "teeter"; String input3 = "aabbcc"; String input4 = "java"; String input5 = ""; String input6 = "abacaba"; // Example with repeating but first unique char System.out.println("Input: \"" + input1 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharFrequencyArray(input1).orElse(' ')); System.out.println("Input: \"" + input2 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharFrequencyArray(input2).orElse(' ')); System.out.println("Input: \"" + input3 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharFrequencyArray(input3).orElse(' ')); System.out.println("Input: \"" + input4 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharFrequencyArray(input4).orElse(' ')); System.out.println("Input: \"" + input5 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharFrequencyArray(input5).orElse(' ')); System.out.println("Input: \"" + input6 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharFrequencyArray(input6).orElse(' ')); } public static Optional<Character> findFirstNonRepeatingCharFrequencyArray(String str) { // Step 1: Handle null or empty string if (str == null || str.isEmpty()) { return Optional.empty(); } // Step 2: Initialize a frequency array for ASCII characters (0-255) int[] charCounts = new int[256]; // Assuming ASCII or extended ASCII // Step 3: Populate the frequency array by iterating through the string once for (char c : str.toCharArray()) { // Ensure character is within array bounds, otherwise handle error or expand array if (c < 256) { charCounts[c]++; } else { // Handle non-ASCII characters if necessary, e.g., using a Map instead // For simplicity, we'll assume ASCII/extended ASCII for this approach System.err.println("Warning: Character out of ASCII range ignored: " + c); } } // Step 4: Iterate through the string again to find the first character with a count of 1 for (char c : str.toCharArray()) { if (c < 256 && charCounts[c] == 1) { return Optional.of(c); } } // Step 5: If no non-repeating character is found return Optional.empty(); } }
Output
Clear
ADVERTISEMENTS