注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
最近这题在两个面试中都遇到了 请大家帮忙看看
给两个字符串s1, s2, scoreWordPair返回一个score, score = 0 如果s1, s2有相同的字符,否则score = s1.length() * s2.length(). 输入一个字符串的array, 找出score最大的两个字符串。
请问除了两个for loop 的暴力解法,还有什么更好的方法吗?(我给出了暴力解法和一些提前终止loop的优化)
public class HighestPair {
public static final String[] WORDS = {
"something",
"red",
"anything",
"green",
"mother",
"yellow",
"father",
"blue",
"foo",
"purple",
"bar",
"orange",
"baz",
"black",
"white",
};
public static void main(String[] args) throws Exception {
String[] words = WORDS;
// The following is a big dataset:
// Charset charset = Charset.forName("ISO-8859-1");
// List<String> result = Files.readAllLines(Paths.get("./data/words_en.txt"), charset);
// words = result.toArray(words);
String[] pair = findHighestScoringPair(words);
System.out.printf("Highest scoring pair of words is '%s' and '%s' with a score of %d.", pair[0], pair[1], scoreWordPair(pair[0], pair[1]));
}
private static int scoreWordPair(String w1, String w2) {
// TODO
}
private static String[] findHighestScoringPair(String[] words) {
//TODO
}
}
|