Find first unique char in a string


  • 0
    P

    class solution {
    public char findFirstUniqChar(String str) {

    }

    }


  • 2
    M
    class Solution {
        public char findFirstUniqChar(String str) {
                char nullChar = '\u0000';
                if (str == null || str.isEmpty()) {
                    return nullChar;
                }
                Set<Character> uniqueChars = new LinkedHashSet<>();
                Set<Character> repeatedChars = new HashSet<>();
                int length = str.length();
                for (int idx = 0; idx < length; idx++) {
                    Character currentChar =  str.charAt(idx);
                    if (uniqueChars.contains(currentChar)) {
                        uniqueChars.remove(currentChar);
                        repeatedChars.add(currentChar);
                    } else if (!repeatedChars.contains(currentChar)) {
                        uniqueChars.add(currentChar);
                    }
                }
                return uniqueChars.isEmpty() ? nullChar : uniqueChars.iterator().next();
            }
        }

  • 0
    C
    char find_first_unique(string str) {
    char result;
    for (int i = 0; i < str.size(); i++) {
    	if (str.find_last_of(str[i]) == i) {
    		result = str[i];
    		break;
    	}
    }
        return result;
    }
    

  • 0
    R

    @miguel.salto one more test condition would be to check if its case sensitive. If not convert the whole string to str.toLowercase() and then proceed


  • 0
    R
    public Character getFirstUniqueChar(String s){
    	Set<Character> uniqueSet=new LinkedHashSet<Character>();
    	Set<Character> repSet=new HashSet<Character>();
    	
    	char[]ch=s.toCharArray();
    for(int i=0;i<ch.length;i++){
    	if(uniqueSet.contains(ch[i])){
    		uniqueSet.remove(ch[i]);
    		repSet.add(ch[i]);
    		
    	}
    	else if(!repSet.contains(ch[i]))
    		uniqueSet.add(ch[i]);
    }
    
    return uniqueSet.isEmpty() ? '' : uniqueSet.iterator().next();
    }

  • 0
    R
    This post is deleted!

  • 0
    T

    @miguel.salto

    One Set would suffice.

    public char firstUniqueChar(String str){
    char nullChar = '\u0000';

    if(str == null || str.length() == 0)
    return nullchar;

    Set<Character> set = new LinkedHashSet<Character>();

    for(int i = 0; i<str.length(); i++){
    char c = str.charAt(i);
    if(!set.add(c)){
    set.remove(c);
    }
    }
    return set.isEmpty()?nullchar:set.iterator().next();
    }


  • 0
    M

    @pankajk83

    I'd first construct frequency table for all characters in a string (it's a map of all characters in a string to their number of occurrences in a string).

    Then I'd iterate on string from left to right (we need the first unique character) and check if it's corresponding number of occurrences is 1. If it is, return it, else continue.

    from collections import defaultdict
    
    def construct_freqs(string):
      freqs = defaultdict(lambda: 0)
      for char in string:
        freqs[char] += 1
      return freqs
    
    def first_unique_char(string):
      freqs = construct_freqs(string)
      for ch in string:
        if freqs[ch] is 1:
          return ch
      return None # threre were no unique characters
    

  • 0
    R

    @mingik collections contains another Dictionary-like datastructor called Counter that is what you need instead of method construct_freq.


  • 0
    R
    import Counter from collections
    
    def first_unique_char(text):
        counters = Counter(text)
        for ch in text:
              if counters[ch] is 1:
                    return ch
    

  • 0
    B

    This program is subset of program to finding all unique elements of array. Here is the program to print all unique elements of an array. C program to find all unique elements. We just have to change this program little bit to work for strings instead of arrays.


  • 0
    N

    can someone tell me whats wrong with this.

    blessings

    Nick

    char firstUnique(string& str)
        {
            for(int i=0; i<str.length(); i++)
                if(str.find_first_of(str[i]) == str.find_last_of(str[i]))
                    return str[i];
            return '!';
        }
    </pre>

  • 0
    E
    #!/usr/bin/python
    
    def firstUnique(string):
      for char in string:
        if string.count(char) == 1:
          return char
    

  • 0
    U

    Java 8 solution to find first unique char in string:

    char firstNonRepeatingLetter = str.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())).entrySet().stream().filter(e -> e.getValue() == 1).map(Map.Entry::getKey).findFirst().orElseGet(() -> '\u0000');
    
    System.out.println("First unique character : " + firstNonRepeatingLetter);
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.