Java 需要更好的方法来查找字符串中的重复单词吗
我需要一种方法来用更少的代码完成相同的操作。这将帮助我更好地理解Java。 以下代码的输出将为: 新的,男孩,下午3点,到Java 需要更好的方法来查找字符串中的重复单词吗,java,Java,我需要一种方法来用更少的代码完成相同的操作。这将帮助我更好地理解Java。 以下代码的输出将为: 新的,男孩,下午3点,到 public class substring { public static void main(String[] args) { // TODO Auto-generated method stub String str= "a new, boy with new haircut boy, 3pm to boy 8pm margian 3pm
public class substring {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str= "a new, boy with new haircut boy, 3pm to boy 8pm margian 3pm to ghost";
String concant = "";
int occurance =0;
str = str.replaceAll(",", "");
System.out.println(str);
String[] subStr = str.split("\\s");
for(String sub:subStr)
{
for (String sub1:subStr) {
if(sub.equals(sub1))
{
occurance++;
if(occurance>=2)
{
if(!concant.contains(sub))
{
if(concant!= "")
concant = concant +", "+ sub;
else
concant = sub;
}
}
}
}
occurance = 0;
}
System.out.println(concant);
}
}
解决方案
您可以利用集合数据结构提供的功能,而不是使用嵌套循环。集合是不能包含重复项的集合。因此,通过检查add方法的真实性,您可以确定重复项
String[] listContainingDuplicates = "a new, boy with new haircut boy, 3pm to boy 8pm margian 3pm to ghost".split("[,\\s]+");
final LinkedHashSet<String> duplicates = new LinkedHashSet<String>();
final Set<String> temp = new HashSet<>();
for (String current : listContainingDuplicates){
if (!temp.add(current))
duplicates.add(current);
}
System.out.println(duplicates.toString());
String[]listcainingduplicates=“一个新的,剪了新发型的男孩,下午3点到晚上8点margian下午3点到ghost”。拆分(“[,\\s]+”;
最终LinkedHashSet duplicates=新LinkedHashSet();
最终设置温度=新的HashSet();
for(当前字符串:包含重复项的列表){
如果(!临时添加(当前))
重复项。添加(当前);
}
System.out.println(duplicates.toString());
将其视为伪代码。您可能需要处理一些边缘情况
只需按空格分割并使用流分组,然后过滤出现次数少于两次的流
String str= "a new, boy with new haircut boy, 3pm to boy 8pm margian 3pm to ghost";
str = str.replaceAll(",", "");
List<String> duplicates = Arrays.stream(str.split(" "))
.filter(s -> !s.isEmpty())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() > 1)
.map(e -> e.getKey())
.collect(Collectors.toList());
String str=“一个新的,留着新发型的男孩,下午3点到晚上8点margian下午3点到ghost”;
str=str.replaceAll(“,”,”);
列表重复项=Arrays.stream(str.split(“”)
.filter(s->!s.isEmpty())
.collect(Collectors.groupingBy(Function.identity()、Collectors.counting())
.entrySet()
.stream()
.filter(e->e.getValue()>1)
.map(e->e.getKey())
.collect(Collectors.toList());
您可以使用哈希
进行有效的检查。循环遍历所有单词,检查单词是否存在,如果不存在,则将其添加到哈希表中,否则将其添加到am空字符串中。我们可以使用hashmap。但是,在输出中只有单词,没有它们的频率,所以hashset也应该工作。它不会给出所有频率为2或更多的单词,看起来代码就是这么做的。需要一种更好的方法来查找字符串中的重复单词,然后忘记频率计数并使用哈希集
。请排除其中一个答案。请记住,没有必要“删除”逗号。就用这个List duplicates=Arrays.stream(str.split(“[,\\s]+”)
Thaks所有这些都很有用。请使用问题中所示的类似字符串进行尝试newdog,dog new
如果保持重复单词的顺序很重要,则LinkedHashSet
应用于重复的,此外,非单词字符(例如逗号)应被删除或视为分隔符。@NikolaiDmitriev这一点没有遗漏。这个问题需要一个更好的方法。这就是它(一旦字符串被正确分割)。感谢您的反馈。我添加了一个正则表达式以更好地满足需求,并使用了LinkedHashSet。我认为该答案符合Suvidh概述的要求,至少与@m.antkowicz功能解决方案相反