繁体   English   中英

如何从字符串列表中找到不重复的字符串

[英]How to find the non-repeating string from the list of string

给出了一个字符串列表,我们必须打印出唯一的字符串。 唯一字符串是在字符串列表中不重复的字符串。

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

我想到了一种算法。

首先对字符串数组进行排序,然后检查相邻的字符串是否相等,然后向前移动,否则它是一个唯一的字符串。 但是这里对字符串数组进行排序的时间复杂度非常高。

任何机构都可以帮助我找到比我的算法更有效的算法吗? 提前致谢。

你可以试试下面

    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);

输出

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

编辑

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

代替 list map cab 用于检查 O(1) 中的包含

解决方案1

您可以在 O(n) 复杂度中解决您的问题。

只需创建一个哈希表来存储单词计数器,然后仅访问count == 1的单词

解决方案2

这个解决方案不是 Liniar 时间,但仍然是一个很好的解决方案。

您可以创建一个带有 count 属性的Trie ,因此很容易找到count == 1的节点

您可以尝试这个简单的 Python 实现,它基于使用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,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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