0
我碰到這個谷歌面試問題,無法找到爲O更好的解決方案(N^2)查找對不重複的字母串的擁有最長的產品
Given a list of words, find two strings S & T such that:
a. S & T have no common character
b. S.length() * T.length() is maximized
我的解決辦法:
//Firstly sort all the strings base on length so that longer strings are at front of list.
sort(words.begin(), words.end());
//Then I have the double for loop that can break as soon as we found a pair
for current string
int found = words.size();
for(int i=0; i<min(found, words.size()-1); i++) {
for(int j=i+1; j<min(found, words.size()); j++) {
if(noSameLetter(words[i], words[j])){
int product = words[i].length() * words[j].length();
maxProduct = max(maxProduct, product);
found = j;
break;
}
}
}
noSameLetter
將採取O(wordLength),我省略了它的代碼。
我試圖在上面的代碼中儘可能地修剪,例如如果我有長度: 10,9,8,7,6,5,4,3,2,1和我已經找到了一對(10,7),我將不嘗試任何一對後7.
該代碼似乎假設沒有兩個單詞是相同的長度 – Paparazzi