I read of a job interview question to write some code for the following:
Write an efficient function to find the first nonrepeated character in a st
enter code here
public class FirstRepeatingAndNonRepeatingElements {
/**
*
* @param elements
* @return
*/
private int firstRepeatedElement(int[] elements) {
int firstRepeatedElement = -1;
if(elements!=null && elements.length>0) {
Set<Integer> setOfElements = new HashSet<>();
for(int i=elements.length-1;i>=0;i--){
if(setOfElements.contains(elements[i])) {
firstRepeatedElement = elements[i];
} else {
setOfElements.add(elements[i]);
}
}
}
return firstRepeatedElement;
}
private int firstNonRepeatedHashSet(int [] elements) {
int firstNonRepatedElement = -1;
Set<Integer> hashOfElements = new HashSet<>();
if(elements!=null && elements.length>0) {
for(int i=elements.length-1;i>=0;i--) {
if(!hashOfElements.contains(elements[i])) {
hashOfElements.add(elements[i]);
firstNonRepatedElement = elements[i];
}
}
}
return firstNonRepatedElement;
}
/**
* @param args
*/
public static void main(String[] args) {
FirstRepeatingAndNonRepeatingElements firstNonRepeatingElement =
new FirstRepeatingAndNonRepeatingElements();
int[] input = new int[]{1,5,3,4,3,5,6,1};
int firstRepeatedElement = firstNonRepeatingElement.
firstRepeatedElement(input);
System.out.println(" The First Repating Element is "
+ firstRepeatedElement);
int firstNonRepeatedElement = firstNonRepeatingElement.
firstNonRepeatedHashSet(input);
System.out.println(" The First Non Repating Element is "
+ firstNonRepeatedElement);
}
More elegant way
def NotRepeatingCharacter(s):
for c in s:
if s.find(c) == s.rfind(c):
return c
return '_'
str = "aabcbdefgh"
lst = list(str)
for i in [(item, lst.count(item)) for item in set(lst)]:
if i[1] == 1:
print i[0],