简体   繁体   中英

How to find the non-repeating string from the list of string

There is given a list of strings out which we have to print the unique strings. Unique string is a string which is not repeated in the list of string.

Ex li = [ram,raj,ram,dev,dev]
unique string = raj. 

I thought of one algorithm.

First sort the String array, then check the adjacent string if its equal then move forward otherwise its a unique string. But here the time Complexity is very high for sorting the string array.

Can any body help me in finding the more efficient algorithm then mine algo? Thanks in advance.

You could try below

    List<String> names = Arrays.asList("ram", "raj", "ram", "dev", "dev");
    Map<String, Long> nameCount = names.stream().collect(Collectors.groupingBy(s -> s, Collectors.counting()));
    List<String> unique = nameCount.entrySet().stream().filter(e -> e.getValue() == 1L).map(Map.Entry::getKey).collect(Collectors.toList());
    System.out.println(nameCount);
    System.out.println(unique);

ouput

{dev=2, raj=1, ram=2}
[raj]

EDIT

    List<String> uniq = new ArrayList<>();
    names.stream().sorted().forEach(n -> {
        if (uniq.contains(n)) {
            uniq.remove(n);
        } else {
            uniq.add(n);
        }
    });

Instead of list map cab be used to check contains in O(1)

Solution 1

You can solve your problem in O(n) complexity.

just create a hash table to store the word counters, and than access just the words with count == 1

Solution 2

This solution is not Liniar time, but stil been a good one.

You can create a Trie with a count property, so will be easy to find the nodes with count == 1

You can try out this simple python implementation, which is based on the concept of using a HashMap :

li = ['ram','raj','ram','dev','dev']
hash = dict()
for item in li:
    if item in hash:
        hash[item] += 1
    else:
        hash[item] = 1

print "unique string(s):",

for key, value in hash.iteritems():
    if value == 1:
        print key,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM