嗨,我正在嘗試解決這個謎語:
給定一個字串陣列,洗掉作為較早字串的變位詞的每個字串,然后按排序順序回傳剩余的陣列。
示例 str = ['code', 'doce', 'ecod', 'framer', 'frame']
代碼和檔案是字謎。從陣列中洗掉 doc 并將第一次出現的代碼保留在陣列中。code 和 ecod 是字謎。從陣列中洗掉 ecod 并將第一個出現代碼保留在陣列中。代碼和成幀器不是字謎。將兩個字串都保留在陣列中。由于 framer 中有額外的 r,因此 framer 和 frame 不是字謎。將兩個字串都保留在陣列中。以升序排列剩余的字串:['code','frame','framer']。
這是我到目前為止得到的:
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;
}
}
結果是:代碼和成幀器。你能幫助我嗎?
uj5u.com熱心網友回復:
您在這里有一些問題,但主要是不要在迭代期間洗掉元素(這幾乎總是會導致不良行為,因為您可能會在這里跳過“幀”)。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但它們將是排序后的版本。
uj5u.com熱心網友回復:
這是一種超級鈍/混淆的 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]);
}
});
uj5u.com熱心網友回復:
在回圈中洗掉時,您應該洗掉或回圈:
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;
}
請拉小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/479293.html
下一篇:輸入大小到底是什么
