Find the first non-repeated character in a string

前端 未结 21 1419
有刺的猬
有刺的猬 2020-12-06 03:53

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

相关标签:
21条回答
  • 2020-12-06 04:30
    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);
    
    }
    
    0 讨论(0)
  • 2020-12-06 04:31

    More elegant way

    def NotRepeatingCharacter(s):
        for c in s:
            if s.find(c) == s.rfind(c):
                return c
        return '_'
    
    0 讨论(0)
  • 2020-12-06 04:32
    str = "aabcbdefgh"
    lst = list(str)
    
    for i in [(item, lst.count(item)) for item in set(lst)]:
        if i[1] == 1:
            print i[0],
    
    0 讨论(0)
提交回复
热议问题