我在面试中遇到了这个问题:
我有一个字符串数组和一个整数k。我的任务是返回由数组中的k个连续字符串组成的第一个最长的字符串。
规则:n是字符串数组的长度,如果n = 0或k> n或k <= 0,则返回“”。
LongestConsec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2)
输出应为“ abigailtheta”
下面是我尝试过的代码。
public class LongestConsecutives
{
public static String LongestConsec(string[] strarr, int k)
{
string final = String.Join("", strarr.OrderByDescending(s=>s.Length).Take(k));
return final;
}
public static void Main()
{
string s1 = LongestConsec(new String[] { "wlwsasphmxx", "owiaxujylentrklctozmymu", "wpgozvxxiu" }, 2); //op="wlwsasphmxxowiaxujylentrklctozmymu"
string s2 = LongestConsec(new string[] { "itvayloxrp", "wkppqsztdkmvcuwvereiupccauycnjutlv", "vweqilsfytihvrzlaodfixoyxvyuyvgpck" }, 2);//op="wkppqsztdkmvcuwvereiupccauycnjutlvvweqilsfytihvrzlaodfixoyxvyuyvgpck"
string s3 = LongestConsec(new String[] { "zone", "abigail", "theta", "form", "libe", "zas" }, -2);//op=""
string s4 = LongestConsec(new String[] { "it", "wkppv", "ixoyx", "3452", "zzzzzzzzzzzz" }, 3);//op="ixoyx3452zzzzzzzzzzzz"
string s5 = LongestConsec(new String[] { "it", "wkppv", "ixoyx", "3452", "zzzzzzzzzzzz" }, 15);//op=""
string s6 = LongestConsec(new String[] { "it", "wkppv", "ixoyx", "3452", "zzzzzzzzzzzz" }, 0);//op=""
string s7 = LongestConsec(new String[] { }, 3);//op=""
string s8 = LongestConsec(new String[] { "zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail" }, 2);//op="abigailtheta"
string s9 = LongestConsec(new String[] { "ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehh" }, 1);//op="oocccffuucccjjjkkkjyyyeehh"
}
}
答案 0 :(得分:2)
您在LINQ中缺少删除重复项的.Distinct()
呼叫。
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;
}
答案 1 :(得分:2)
与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));