我在一轮面试中被问到你有两个段落
P1 = I am Lalit
P2 = Lalit Kumar
现在找到常见的单词,而不是字符,然后只打印不常见的。
Ex: I am Kumar
解决这个问题的最佳方法是什么?
最佳答案
这可能有点矫枉过正,但我会拆分两个字符串,将它们收集到一个 LinkedHashMap
(以保留原始顺序)并计算每个字符串出现的次数,然后过滤掉非唯一条目:
String p1 = "I am Lalit";
String p2 = "Lalit Kumar";
String result =
Stream.concat(Arrays.stream(p1.split("\\s")), Arrays.stream(p2.split("\\s")))
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new,
Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.joining(" "));
关于 java |如何从字符串中删除常用词然后连接不常用词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51238453/