Reputation: 23
I have a strange issue to print the first non repeated character from String.
If I put for example "sasso" as String it gives me back correctly: 'a'
but if I try with "sassa" I wonder why it gives me back: "s"
public class FirstChar {
public char findFirst(String s) {
boolean[] letters = new boolean[26];
char[] firstLetter = new char[26];
for (int i = 0; i < s.length(); i++) {
if (letters[s.charAt(i) - 97] &&
(firstLetter[0] != (s.charAt(i)))) {
System.out.println( firstLetter[0]);
return firstLetter[0];
}
letters[s.charAt(i) - 97] = true;
char c = (char) (s.charAt(i));
firstLetter[i] = c;
}
System.out.println(firstLetter[1]);
return firstLetter[1];
}
public static void main(String args[]) {
FirstChar obj = new FirstChar();
obj.findFirst("sassa");
}
}
Upvotes: 0
Views: 50
Reputation: 603
You need to ensure that firstLetter acts as a queue of non repeating characters and remove from it, the moment repeated character is encountered. You are always returning character at 0th or 1st position without overwriting firstLetter array elements.
In case is sassa
, when last character a
is encountered, conditions in first if
evaluate to true and thus return s
which is the first character stored in the firstLetter array.
You need HashMap and Queue to achieve this
Upvotes: 1