在这之后我完全脑筋急转弯,我需要找到两个文件之间最长的公共子字符串,一个小文件和一个大文件。我什至不知道从哪里开始搜索,这是我到目前为止所拥有的
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MyString
{
public static void main (String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("MobyDick.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("WarAndPeace.txt"));
String md, wp;
StringBuilder s = new StringBuilder();
while ((md = br.readLine()) != null)
{
s.append(md).append(" ");
}
md = s + "";
s.setLength(0);
while ((wp = br2.readLine()) != null)
{
s.append(wp).append(" ");
}
wp = s + "";
s.setLength(0);
md = md.replaceAll("\\s+", " "); //rids of double spaces
wp = wp.replaceAll("\\s+", " "); //rids of double spaces
}
}
到目前为止,我所做的是将每个文件放入一个字符串生成器中,然后放入一个字符串中以消除双空格(它在 MobyDick.txt 上出现了很多)。我找到了这段代码
public static String longestSubstring(String str1, String str2) {
StringBuilder sb = new StringBuilder();
if (str1 == null || str1.isEmpty() || str2 == null || str2.isEmpty())
return "";
// ignore case
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
// java initializes them already with 0
int[][] num = new int[str1.length()][str2.length()];
int maxlen = 0;
int lastSubsBegin = 0;
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
if ((i == 0) || (j == 0))
num[i][j] = 1;
else
num[i][j] = 1 + num[i - 1][j - 1];
if (num[i][j] > maxlen) {
maxlen = num[i][j];
// generate substring from str1 => i
int thisSubsBegin = i - num[i][j] + 1;
if (lastSubsBegin == thisSubsBegin) {
//if the current LCS is the same as the last time this block ran
sb.append(str1.charAt(i));
} else {
//this block resets the string builder if a different LCS is found
lastSubsBegin = thisSubsBegin;
sb = new StringBuilder();
sb.append(str1.substring(lastSubsBegin, i + 1));
}
}
}
}}
return sb.toString();
}
此代码有帮助,但仅适用于小文件,每次我使用大文件运行它时,都会出现“内存不足:java 堆空间”错误。我需要正确的算法来摆脱堆空间问题,而且我不能增加 java 内存,任何人都可以帮助或指出正确的方向吗?