【发布时间】:2022-01-19 16:00:08
【问题描述】:
编辑:所以我花了更多时间思考并找到了解决方案,如果您需要它的代码,我对其进行了编辑,所以现在是正确的,没有错误。感谢所有试图提供帮助的人,祝您有美好的一天!
给出两个大小相等的字符串。确定第一个字符串中的每个字符是否可以唯一地替换为第二个字符串中的字符,从而使两个字符串相等。同时显示两个字符串之间对应的字符对。
示例 1:
对于输入数据:
aab
ttd
控制台会显示:
True
a => t
b => d
示例 2:
对于输入数据:
tab
ttd
控制台会显示:
False
在第二个例子中,答案是错误的,因为字符“a”没有唯一的对应关系:“t”和“d”都对应它。
这是我的代码:
using System;
命名空间问题eJM { 课堂节目 { 静态无效主要(字符串 [] 参数) { string firstPhrase = Convert.ToString(Console.ReadLine()); 字符串 secondPhrase = Convert.ToString(Console.ReadLine()); 字符串 aux1 = string.Empty,aux2 = string.Empty; 布尔 x = true;
for (int i = 0; i < firstPhrase.Length; i++)
{
if (!aux1.Contains(firstPhrase[i]))
{
aux1 += firstPhrase[i];
}
}
for (int i = 0; i < secondPhrase.Length; i++)
{
if (!aux2.Contains(secondPhrase[i]))
{
aux2 += secondPhrase[i];
}
}
if (aux1.Length != aux2.Length)
{
Console.WriteLine("False");
}
else
{
for (int i = 0; i < firstPhrase.Length - 2; i++)
{
for (int j = 1; j < secondPhrase.Length - 1; j++)
{
if (firstPhrase[i] == firstPhrase[j] && secondPhrase[i] == secondPhrase[j])
{
x = true;
}
else if (firstPhrase[i] != firstPhrase[j] && secondPhrase[i] != secondPhrase[j])
{
x = true;
}
else if (firstPhrase[i] == firstPhrase[j] && secondPhrase[i] != secondPhrase[j])
{
x = false;
break;
}
else if (firstPhrase[i] != firstPhrase[j] && secondPhrase[i] == secondPhrase[j])
{
x = false;
break;
}
}
}
Console.WriteLine(x);
aux1 = string.Empty;
aux2 = string.Empty;
if (x == true)
{
for (int i = 0; i < firstPhrase.Length; i++)
{
if (!aux1.Contains(firstPhrase[i]))
{
aux1 += firstPhrase[i];
}
}
for (int i = 0; i < secondPhrase.Length; i++)
{
if (!aux2.Contains(secondPhrase[i]))
{
aux2 += secondPhrase[i];
}
}
for (int i = 0; i <= aux1.Length - 1; i++)
{
for (int j = 1; j <= aux2.Length; j++)
{
if (aux1[i] == aux1[j] && aux2[i] == aux2[j])
{
Console.WriteLine(aux1[i] + " => " + aux2[i]);
break;
}
else if (aux1[i] != aux1[j] && aux2[i] != aux2[j])
{
Console.WriteLine(aux1[i] + " => " + aux2[i]);
break;
}
}
}
}
}
}
}
}
【问题讨论】:
-
我想我会用字典来做这个;同时对两个数组进行步进,以 array1char 作为键,array2char 作为值填充字典。如果我添加了一些已经存在的东西(提示;TryGetValue 或 ContainsKey,然后再添加并相应地更改行为),那么已经存在的值必须与当前的 array2char 相同,否则提前退出循环并返回假。如果到达循环的末尾,则返回 true。字典包含您将打印的映射,如果它是真的。看起来像家庭作业;不打算编码它,GL!
-
提示:使用
Dictionary<char, char>。
标签: c# arrays string algorithm sorting