计算字符串匹配数 [英] Count the Number of String Matches
本文介绍了计算字符串匹配数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获得列表中最小的字符串匹配.尽管我成功地做到了,但问题是我想算出已经进行了多少次比赛计数:
I want to get the smallest match of strings in the list. Though I'm successful doing so but the problem is i want to count that how many match counts have been made so:
List<String> mylist=new LinkedList<String>();
Set<String> result=new LinkedHashSet<String>();
mylist.add("interpreter");
mylist.add("interprete");
mylist.add("interpret");
mylist.add("developed");
mylist.add("develops");
mylist.add("develop");
mylist.add("interpret");
String small="";
Collections.sort(mylist);
Collections.reverse(mylist);
for(int i=0;i<mylist.size();i++)
{
small=mylist.get(i);
for(int j=i;j<mylist.size();j++)
{
if(small.contains(mylist.get(j)))
{
small=mylist.get(j);
}
}
result.add(small);
}
for (String string : result) {
System.out.println(string);
}
因此输出应为:
interpret=4
develop=4
我尝试使用以下代码时出现问题:
Problem occurs with the following code i am trying:
List<String> mylist=new LinkedList<String>();
Set<String> result=new LinkedHashSet<String>();
mylist.add("interpreter");
mylist.add("interprete");
mylist.add("interpret");
mylist.add("developed");
mylist.add("develops");
mylist.add("develop");
mylist.add("interpret");
mylist.add("crawler");
mylist.add("crawl");
mylist.add("mobile");
mylist.add("mob");
mylist.add("juni");
mylist.add("junis");
Collections.sort(mylist);
Collections.reverse(mylist);
String small="";
int c=0;
for(int i=0;i<mylist.size();i++)
{
c+=1;
small=mylist.get(i);
for(int j=i;j<mylist.size();j++)
{
if(small.contains(mylist.get(j)))
{
small=mylist.get(j);
c+=1;
}
}
result.add(small);
}
for (String string : result) {
System.out.println(string+"="+c);
}
有人可以帮我吗!
推荐答案
在您的代码中输入@jambriz的答案:
Putting @jambriz's answer in your code:
1.使用HashMap
1.Use a HashMap
HashMap<String, Integer> result= new LinkedHashMap<String, Integer>();
2.仅当值是新值或计数小于以前的计数时,才在哈希映射中添加该值,而不是现在的result.add(small);
.另外,在此处设置c=0
2.Instead of result.add(small);
now, add the value in hashmap only if the value is new or the count is less than the previous count. Also, set c=0
here
if (!result.containsKey(small) || result.get(small) < c)
result.put(small, c);
c = 0;
3.在最后打印您的结果:
3.At Last print your results:
for (String key : result.keySet())
System.out.println(key + ": " + result.get(key));
这篇关于计算字符串匹配数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文