我的问题陈述:
一个文件中将有一组给定的单词(>5000个单词)。我们需要返回每个字符串(一组字谜)中由逗号(,)分隔的字谜列表
例如:[改变,稍后,分开,陷阱,肘部,下面,听,沉默,紧张]
例外情况:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:265)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:239)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:231)
at java.util.ArrayList.add(ArrayList.java:462)
at FindAnagrams01.anagramsList(FindAnagrams01.java:25)
at FindAnagrams01.main(FindAnagrams01.java:7)
我的代码是:
public static List<String> anagramsList(String filePath) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String str = br.readLine();
List<List<String>> result = new ArrayList<List<String>>(10000);
HashMap<String, ArrayList<String>> map = new HashMap<String,ArrayList<String>>(10000);
while(str != null) {
char[] arr = new char[26];
for(int i = 0; i < str.length(); i++) {
arr[str.charAt(i) - 'a']++;
}
String ns = new String(arr);
if(map.containsKey(ns)){
map.get(ns).add(str);
} else {
ArrayList<String> al = new ArrayList<String>(10000);
al.add(str);
map.put(ns, al);
}
}
br.close();
result.addAll(map.values());
String res[] = new String[10000];
for(int i = 0; i < result.size(); i++) {
int isIntial = 0;
for(String j : result.get(i)) {
if ((result.get(i).size()) > 1) {
if (isIntial == 0) {
res[i] = j;
isIntial = 1;
}
else
res[i] += "," + j;
}
}
}
List<String> angrms = new ArrayList<String>(10000);
for (int i = 0; i < res.length; i++) {
if (res[i] != null)
angrms.add(res[i]);
}
return angrms;
}