嗨,我想解开这个谜团:
给定一个字符串数组,删除每个字符串,这些字符串是前一个字符串的一个字谜,然后按排序顺序返回其余的数组。
例如str = 'code','doce','ecod','framer','frame‘
代码和doce都是字谜。从数组中删除doce,并保留数组中的第一个出现代码。代码和生态是一个谜。从数组中删除ecod,并保留数组中的第一个出现代码。代码和框架不是字谜。将两个字符串保存在数组中。框架和框架不是字谜,因为在框架中的额外r。将两个字符串保存在数组中。按升序排列剩余的字符串:“代码”、“框架”、“框架”。
到目前为止,我得到的是:
static void Main(string[] args)
{
List<string> str = new List<string>();
str.Add("code");
str.Add("doce");
str.Add("ecod");
str.Add("framer");
str.Add("frame");
foreach (var item in funWithAnagrams(str))
{
Console.WriteLine(item);
}
}
public static List<string> funWithAnagrams(List<string> text)
{
for (int i = 0; i < text.Count; i++)
{
for (int j = 1 ; j < text.Count; j++)
{
if (text[i].Length==text[j].Length )
{
if (isAnagram(text[i],text[j]))
{
text.RemoveAt(j);
}
}
}
}
text.Sort();
return text;
}
public static bool isAnagram(string a, string b)
{
char[] arr1 = a.ToCharArray();
Array.Sort(arr1);
char[] arr2 = b.ToCharArray();
Array.Sort(arr2);
string c = new string(arr1);
string d = new string(arr2);
if (c==d)
{
return true;
}
else
{
return false;
}
}其结果是:代码和框架。你能帮帮我吗?
发布于 2022-05-20 19:22:12
这里有一些问题,但主要是在迭代期间不删除元素(这几乎总是导致错误的行为,因为您可能跳过这里的“框架”)。这种行为在foreach语句中实际上是非法的。
这是我刚做的一个工作版本
var anagrams = new List<string>() {
"code",
"doce",
"ecod",
"framer",
"frame"
};
var noAnagrams = new List<string>();
var result = new List<string>();
foreach (var a in anagrams) {
var arr1 = a.ToCharArray();
Array.Sort(arr1);
var sorted = new string(arr1);
if (!noAnagrams.Contains(sorted)) {
noAnagrams.Add(sorted);
result.Add(a);
}
}最后,result = {code, frame, framer}
我在这里使用了两个不同的列表来保留原始字谜的正确拼写。您将在noAnagrams中具有相同的值,但它们将是排序版本。
发布于 2022-05-20 19:46:04
在循环删除时,应该移除或循环:
for (int i = 0; i < text.Count; i++)
for (int j = i + 1 ; j < text.Count; ) // note abscence of ++j
if (text[i].Length == text[j].Length && isAnagram(text[i],text[j])
text.RemoveAt(j); // either remove
else
j++; // or go to the next item
text.Sort();更好的方法是排序:对单词中的字母进行排序并进行比较:
odce => cdeo
code => cdeo代码:
public static List<string> funWithAnagrams(List<string> text) {
if (text is null)
throw new ArgumentNullException(nameof(text));
var unique = new HashSet<string>();
for (int i = 0; i < text.Count; ) // no i++ here
if (unique.Add(string.Concat(text[i].OrderBy(c => c))))
i += 1; // either go to the next word
else
text.RemoveAt(i); // or remove current word
text.Sort();
return text;
}拜托,小提琴
发布于 2022-05-20 19:52:47
这是一种超级迟钝/模糊的LINQ方法.
Dictionary<int, string> result = new Dictionary<int, string>();
str.Select((s, i) => new { s, i })
.ToDictionary(x => x.i, x =>
new string(x.s.ToCharArray()
.OrderBy(s => s)
.ToArray()))
.ToList()
.ForEach(pair => {
if (!result.ContainsValue(pair.Value))
{
result.Add(pair.Key, pair.Value);
Console.WriteLine(str[pair.Key]);
}
});https://stackoverflow.com/questions/72323745
复制相似问题