justinmflanagan72@googlemail.com
BAN USERThe following solution avoids the worst case O(n2) by removing the nested loop. Does not use the java api either. Question, ideally would state whether it needs to be solved using raw code or using Java API.
public static String findFirstNonRepeatingChar(String string) {
//ascii mapping of char a.
int ASCII_VALUE_A=97;
//0==a, 1==b, 2==c ...
int[] charCounts = new int[26];
//the order in which the chars appeared in the supplied string
char[] charSequence = new char[26];
int charSequenceCount=0;
for(char character : string.toLowerCase().toCharArray()) {
if(character != ' ') {
//Have we seen this char before?
int countIndex = ((int)character)-ASCII_VALUE_A;
int count = charCounts[countIndex];
//new char not seen before so store in the char sequence
if(count == 0)
charSequence[charSequenceCount++] = character;
//increment the number of occurrences count for the given char
charCounts[countIndex]=++count;
}
}
//iterate over the chars in the order they appeared in the supplied string
for(int i=0; i<charSequenceCount; i++) {
char c = charSequence[i];
if(charCounts[((int)c)-ASCII_VALUE_A]==1) {
return c+"";
}
}
return "No unique characters in sentence : " + string;
}
Apologies, it does the api for the toLowerCase() call.
- justinmflanagan72@googlemail.com January 28, 2016