基于全字短语的最长最常见子字符串



我一直在围绕这个主题做很多研究,不能轻易破解这个。我在网上遇到过很多有价值的解决方案,可以根据字符解决这个问题,但是您将如何基于全单词短语解决此问题以避免结果返回在短语开头或结尾包含部分单词的短语?

例如,给定一个字符串数组,输出将是数组中大多数(不是全部(字符串中包含的最常见的全单词短语。

下面的这个例子是我迄今为止找到的最接近的例子,但它只工作了大约一半的时间,并且包括部分单词结果,这不是我想要的。我相信以前有人解决过这个问题。

// 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);

最新更新