java实现字符串数组最长公共子串
时间: 2024-06-16 19:06:49 浏览: 18
在Java中,使用动态规划的方法来实现数组的最长公共子串。下面一个示例代码:
```java
public class LongestCommonSubstring {
public static String findLongestCommonSubstring(String[] strings) {
if (strings == null || strings.length == 0) {
return "";
}
String firstString = strings;
int maxLength = 0;
int endIndex = 0;
for (int i = 0; i < firstString.length(); i++) {
for (int j = i + 1; j <= firstString.length(); j++) {
String substring = firstString.substring(i, j);
boolean isCommonSubstring = true;
for (int k = 1; k < strings.length; k++) {
if (!strings[k].contains(substring)) {
isCommonSubstring = false;
break;
}
}
if (isCommonSubstring && substring.length() > maxLength) {
maxLength = substring.length();
endIndex = j;
}
}
}
return firstString.substring(endIndex - maxLength, endIndex);
}
}
```
使用示例:
```java
String[] strings = {"abcdefg", "abcfgh", "abcfghi"};
String longestCommonSubstring = LongestCommonSubstring.findLongestCommonSubstring(strings);
System.out.println("Longest common substring: " + longestCommonSubstring);
```
输出结果:
```
Longest common substring: abcf
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)