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