我围绕这个主题做了很多研究,但无法轻易解决这个问题。我在网上遇到了很多有值(value)的解决方案来解决基于字符的这个问题,但是如何基于全词短语来解决这个问题,以避免结果返回一个开头包含部分单词的短语或短语的结尾?
例如,给定一个字符串数组,输出将是数组中大多数(不是全部)字符串中包含的最常见的全字短语。
下面的示例是迄今为止我发现的最接近的示例,但它只在大约一半的时间内有效,并且包含部分单词结果,这并不完全是我所追求的。我确信以前有人已经解决过这个问题。
// function to find the stem (longest common
// substring) from the string array
public static String findstem(String arr[])
{
// Determine size of the array
int n = arr.length;
// Take first word from array as reference
String s = arr[0];
int len = s.length();
String res = "";
for (int i = 0; i < len; i++) {
for (int j = i + 1; j <= len; j++) {
// generating all possible substrings
// of our reference string arr[0] i.e s
String stem = s.substring(i, j);
int k = 1;
for (k = 1; k < n; k++)
// Check if the generated stem is
// common to all words
if (!arr[k].contains(stem))
break;
// If current substring is present in
// all strings and its length is greater
// than current result
if (k == n && res.length() < stem.length())
res = stem;
}
}
return res;
}
// Driver Code
public static void main(String args[])
{
String arr[] = { "grace", "graceful", "disgraceful",
"gracefully" };
String stems = findstem(arr);
System.out.println(stems);
}
最佳答案
这是否符合您的预期。它只是检查是否有任何单词是其自身和其他单词的子串。
如果你想检查真实的单词子串,你需要引用一些字典,这将非常耗时。
String arr[] = { "grace", "graceful", "disgraceful",
"gracefully" };
String save = "";
int count = 0;
for (int i = 0; i < arr.length && count != arr.length; i++) {
count = 0;
for (int k = 0; k < arr.length; k++) {
if (arr[k].contains(arr[i])) {
count++;
save = arr[i];
}
}
}
System.out.println(save);
关于java - 基于全词短语的最长最常见子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59595573/