[英]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) 中的包含
您可以尝试这个简单的 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.