【发布时间】:2021-10-04 09:47:08
【问题描述】:
我正在尝试获取单词列表并比较每个单词。如果单词是相似的或子字符串,它将返回有多少单词相似的计数。如果没有找到,它将返回 -1。
当我运行输入{similar, liar, not,knot, java}... output{not}的代码时,什么时候应该输出{[similar, liar], [knot, not]} count = 2。但如果我添加这些词,它会起作用,我不知道为什么。输入:mass, as, hero, superhero, not output: as, hero count is = 2
public static List<String> stringMatching(String [] words){
HashSet<String> temp = new HashSet<>();
int n = words.length;
int count = 0;
for(int i = 0; i < n-1; i++) {
String currentWord = words[i];
for(int j = i+1; j<n; j++) {
String nextWord = words[j];
if(currentWord.contains(nextWord)) {
temp.add(nextWord);
count++;
}
if(nextWord.contains(currentWord)) {
temp.add(currentWord);
count++;
}
}
}
System.out.println(count);
return new ArrayList<String>(temp);
public static void main(String[] args){
String[] words = {"mass", "as", "hero", "superhero", "not"};
List<String> listM = stringMatching(words);
for(String x: listM) {
System.out.println(x+ " ");
}
}
【问题讨论】:
-
你如何定义“相似”?
-
在您的示例中,“liar”这个词并没有完全出现在“similar”字符串中,因此子字符串不会匹配它;
"similar".contains("liar")是假的。 -
在你的“应该输出”的例子中,“骗子”这个词不是“相似”的子字符串,所以正如波西米亚问的那样,你如何定义字符串到相似吗?
-
我在看类似的字符...抱歉可能更像是一个字谜。