2 回答
TA贡献1878条经验 获得超4个赞
您.Distinct()在 LINQ 中缺少删除重复项的调用。
public static String LongestConsec(string[] strarr, int k)
{
string final = String.Join("",
strarr.Distinct() // Remove Duplicates
.OrderByDescending(s => s.Length) // Order by Length
.Take(k) // Take from List
);
return final;
}
在此修改后,您将获得预期的输出:
string target = LongestConsec(new string[] { "zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"}, 2);
// target = "abigailtheta"
但是您仍然缺少IF完成您描述的规则的案例:
如果 n = 0 或 k > n 或 k <= 0 返回“”
更新
正如 Vladimir Pavelka 在评论中指出的那样,您只需要一种方法来存储词序的初始索引。你可以用这样的Dictionary东西来做到这一点:
public static String LongestConsec(string[] strarr, int k)
{
var dict = new Dictionary<string, int>();
for (int i = 0; i < strarr.Length; i++)
{
if (!dict.ContainsKey(strarr[i])) // Preventing duplicates
{
dict.Add(strarr[i], i + 1);
}
}
string final = String.Join("",
dict.OrderByDescending(s => s.Key.Length)
.Take(k)
.OrderBy(s => s.Value)
.Select(s => s.Key)
);
return final;
}
TA贡献1859条经验 获得超6个赞
与 Smartis 讨论后:
public static String LongestConsec(string[] strarr, int k) =>
String.Join("",
strarr.Distinct() // note: this won't change order
.Select((s, idx) => (s, idx)) // store initial index
.OrderByDescending(x => x.s.Length) // longest words first
.Take(k)
.OrderBy(x => x.idx) // restore original order
.Select(x => x.s));
- 2 回答
- 0 关注
- 163 浏览
添加回答
举报