-1
給定一個大文件,包括了幾句 (例如,W1,W2,W3)一個空頭格局,發現有任何 爲了所有單詞的最短字符串(例如W2 foo bar dog W1 cat W3 - 是一種有效模式)查找最小長度子字符串包含所有的字符串
我將「大文檔」構造爲一個字符串列表。我相信我的解決方案是O(nlog(n)),但我不確定(我也不確定它是否正確)。有更快的方法嗎?請注意,下面pseudocoded Java,所以顯然不會編譯,但我相信信息是明確的:
main(){
List<String> wordsToCheckFor;
List<String> allWords;
int allWordsLength = allWords.length;
int minStringLength = POS_INFINITY;
List<String> minString;
//The idea here is to divide and conquer the string; I will first
//check the entire string, then the entire string minus the first
//word, then the entire string minus the first two words, and so on...
for(int x = 0; x < allWordsLength; x++){
if(checkString(allWords, wordsToCheckFor) && (allWords.length < minStringLength)){
minString = allWords;
minStringLength = allWords.length();
}
allWords.remove(0);
}
System.out.println(minString);
}
checkString(List<String> allWords, List<String> wordsToCheckFor){
boolean good = true;
foreach(String word : wordsToCheckFor){
if(!allWords.contains(word))
good = false;
}
return good;
}
這至少是O(n * n)。你正在調用List.contains(這是O(n))n次。這也是不正確的。如果模式位於字符串的開頭,它將不起作用。例如:'W1 W2 W3 a b c' – 2014-11-14 23:56:45