我正在编写一些 java 代码,我编写了一个方法,对于测试输入,执行时间超过 5 秒,我真的很想将其保持在 5 秒以内
private static String getShortestSub(ArrayList<String> paraWordsList,
ArrayList<Integer> paraWordsIndexes,
ArrayList<Integer> lowFreqIndexes) {
long d = System.currentTimeMillis();
// Finding the substring
int startTxtIndex = 0, endTxtIndex = 0;
int tempLength = paraWordsList.size();
for (int i = 0; i < lowFreqIndexes.size(); i++)
{
int point = lowFreqIndexes.get(i), startIndex = 0;
HashSet<String> frame = new HashSet<String>();
// index is the indexes of paraWordsIndexes
startIndex =paraWordsIndexes.indexOf(point);
for (int index = paraWordsIndexes.indexOf(point); index >= 0; index--)
{
if (frame.add(paraWordsList.get(paraWordsIndexes.get(index))))
{
startIndex = index;
if (frame.size() == K
|| (paraWordsIndexes.get(startIndex) - point) >= tempLength)
index = -1;
}
}
frame.clear();
for (int start = startIndex, index = startIndex; start <= paraWordsIndexes
.indexOf(point) && index < paraWordsIndexes.size(); index++)
{
int tempStart = paraWordsIndexes.get(start), tempEnd = paraWordsIndexes.get(start);
int currIndex = paraWordsIndexes.get(index);
String word = paraWordsList.get(currIndex);
if ((tempStart - point) >= tempLength) break;
if ((tempStart - currIndex) >= tempLength) break;
frame.add(word);
if (frame.size() == K)
{
tempEnd = currIndex;
int newLength;
if ((newLength = tempEnd - tempStart) > 0)
if (tempLength > newLength)
{
tempLength = newLength;
startTxtIndex = tempStart;
endTxtIndex = tempEnd;
if (K == (tempLength+1)) {
i = lowFreqIndexes.size();
break;
}
}
frame.clear();
tempStart = paraWordsList.size();
start++;
index = start - 1;
}
}
frame.clear();
System.out.println(System.currentTimeMillis() - d);
}
String[] result = paraText.split(" ");
ArrayList<String> actualParaWordsList = new ArrayList<String>(
Arrays.asList(result));
return textCleanup(actualParaWordsList.subList(startTxtIndex,
endTxtIndex + 1).toString());
}