question
Devise an algorithm to find the first character that occurs only once in an input string.
ex. firstUniqueCharacter("chickenhi")
returns 'k'
Note: Email incorrectly displayed 'i'
ex. firstUniqueCharacter("chickenhi")
returns 'k'
Note: Email incorrectly displayed 'i'
An O(n^2) solution is incorrect. Try separating the string by letters.
The most efficient solution for this problem involves counting the occurrence of each
letter and then iterating through the string again to search for the first character
with a count of 1.
firstUniqueCharacter(String input)
int[] count = new int[26];
// Convert to lower case for easier processing
input = input.toLowerCase();
for (i = 0; i < input.length(); i++)
// Typecast to int to obtain ASCII value in some languages
if (count[input.charAt(i) - 'a'] == null)
count[input.charAt(i) - 'a'] = 1;
else
count[input.charAt(i) - 'a']++;
for (i = 0; i < input.length(); i++)
if (count[input.charAt(i) - 'a'] == 1)
return input.charAt(i);
return null;