Java Online Compiler
Example: First Non-Repeating Character (Array) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// First Non-Repeating Character (Array) 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: " + firstUniqCharArray(s1)); String s2 = "loveleetcode"; System.out.println("String: \"" + s2 + "\", First non-repeating char index: " + firstUniqCharArray(s2)); String s3 = "aabb"; System.out.println("String: \"" + s3 + "\", First non-repeating char index: " + firstUniqCharArray(s3)); } public static int firstUniqCharArray(String s) { // Step 1: Create an integer array to store character frequencies. // Array size 256 accommodates all possible extended ASCII characters (0-255). int[] charCounts = new int[256]; // Step 2: Iterate through the string to populate the frequency array. // The character's ASCII value is automatically cast to an int and used as the index. for (char c : s.toCharArray()) { charCounts[c]++; } // Step 3: Iterate through the string again to find the first character with a count of 1. for (int i = 0; i < s.length(); i++) { if (charCounts[s.charAt(i)] == 1) { return i; // Found the first non-repeating character } } // Step 4: If no non-repeating character is found, return -1. return -1; } }
Output
Clear
ADVERTISEMENTS