如下这种方法能成功,却击败了0.00%,后期我会对写出新的方法
public string LongestWord(string[] words) {
var wordsSet = new HashSet<string>();
var resultSet = new HashSet<string>();
Array.Sort(words);
for(var i = 0; i < words.Length; i++) {
wordsSet.Add(words[i]);
}
for(var i = words.Length - 1; i >= 0; i--) {
if(IsCompleteWord(words[i], wordsSet)) {
resultSet.Add(words[i]);
}
}
var list = resultSet.OrderByDescending(r => r.Length).ToList();
return list.Where(r => r.Length == list[0].Length).Min();
}
private static bool IsCompleteWord(string word, HashSet<string> wordsSet) {
for(var i = 0; i < word.Length; i++) {
if(!wordsSet.Contains(word.Substring(0, i + 1))) return false;
}
return true;
}
新的思路:
后期更新...
2019/12/04
还是用哈希
思路:排序、 如果是一个的话加如hashset先将w加入
wo,判断wo是否包含 wo-1 =w.如果包含w。将wo加入其中,三想表达式求出最大的字符串就ok了
public static string LongestWord(string[] words)
{
if (words == null)
return null;
Array.Sort(words);
// word with prefixes in the dictionary
var visitedPrefix = new HashSet<string>();
string maximumWord = "";
foreach (var word in words)
{
var length = word.Length;
// think carefully about this reason using w, wo, wor, word
string str = word.Substring(0, length - 1);
if (length == 1 || visitedPrefix.Contains(str))
{
// keep lexico order - apple will be checked before apply
maximumWord = word.Length > maximumWord.Length ? word : maximumWord;
visitedPrefix.Add(word);
}
}
return maximumWord;
}