Java Online Compiler
Example: First Non-Repeating Character (HashMap) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// First Non-Repeating Character (HashMap) import java.util.HashMap; import java.util.Map; import java.util.Scanner; // Included as per code pattern, though not strictly needed for the core logic of this problem. public class Main { public static void main(String[] args) { String s1 = "leetcode"; System.out.println("String: \"" + s1 + "\", First non-repeating char index: " + firstUniqCharHashMap(s1)); String s2 = "loveleetcode"; System.out.println("String: \"" + s2 + "\", First non-repeating char index: " + firstUniqCharHashMap(s2)); String s3 = "aabb"; System.out.println("String: \"" + s3 + "\", First non-repeating char index: " + firstUniqCharHashMap(s3)); } public static int firstUniqCharHashMap(String s) { // Step 1: Create a HashMap to store character frequencies. // Key: character, Value: count of occurrences Map<Character, Integer> charCounts = new HashMap<>(); // Step 2: Iterate through the string to populate the frequency map. // For each character, increment its count. for (char c : s.toCharArray()) { charCounts.put(c, charCounts.getOrDefault(c, 0) + 1); } // Step 3: Iterate through the string again to find the first character with a count of 1. // The order of iteration is crucial here to find the *first* non-repeating character. for (int i = 0; i < s.length(); i++) { if (charCounts.get(s.charAt(i)) == 1) { return i; // Found the first non-repeating character } } // Step 4: If no non-repeating character is found after checking all characters, return -1. return -1; } }
Output
Clear
ADVERTISEMENTS