我在面试中遇到了这个问题:
我得到了一个字符串数组 strarr 和一个整数 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"
}
}
最佳答案
您在 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
案例:
if n = 0 or k > n or k <= 0 return ""
更新
正如 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;
}
关于c# - 返回c#中数组中取n个连续字符串组成的第一个最长的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51167686/