xxxxxxxxxx
def first_unique_char(string):
char_count = {}
# Calculate frequency count of each character
for char in string:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# Find the first unique character
for char in string:
if char_count[char] == 1:
return char
# If no unique characters found
return None
# Example usage
input_string = "leetcode"
first_unique = first_unique_char(input_string)
print("First unique character:", first_unique)
xxxxxxxxxx
//saiyam9934
public class Main {
public static int firstUniqChar(String s) {
int[] oc = new int[26];
// Store frequency of each character of s
for (char c : s.toCharArray()) {
oc[c - 'a']++;
}
// First character with frequency = 1 is the answer
for (int i = 0; i < s.length(); i++) {
if (oc[s.charAt(i) - 'a'] == 1) {
return i;
}
}
// No character with frequency = 1
return -1;
}
public static void main(String[] args) {
String input = "leetcode";
int result = firstUniqChar(input);
System.out.println("Index of the first unique character: " + result);
}
}