【发布时间】:2020-07-31 23:35:53
【问题描述】:
所以我需要一些锻炼帮助,我被困住了!放轻松,我对此很陌生。练习如下:
给定两个长度相等的 char 数组,确定第一个数组中的每个字符是否可以唯一地替换为第二个数组中的字符,以使两个数组相等。显示两个数组之间的字符对。
示例 1:
给定以下输入:aab 和 ttd,控制台将显示:
True
a => t
b => d
示例 2:
给定以下输入:aba 和 ttd,控制台将显示:
False
在第二个示例中,答案是 False,因为字符 a 没有唯一的替换符:t 和 d 都对应。
我一直在为此烦恼,老实说,我觉得我什至无法再思考了。已经对代码进行了很多次调整,以至于我几乎不再理解它了。虽然它仍然通过了第一个测试,但似乎一直未能通过更长的字符串输入的测试。例如输入:ala bala portocala 和cuc dcuc efghijcuc,控制台显示True,然后是对,这是不对的。下面你有我的 POS 码,欢迎任何建议。
static void Main(string[] args)
{
string a = Console.ReadLine();
string b = Console.ReadLine();
string one = string.Empty;
string two = string.Empty;
bool res = false;
int count = 0;
for (int i = 0; i < a.Length; i++)
{
if (!one.Contains(a[i].ToString()))
{
if (!two.Contains(b[i].ToString()))
{
one += a[i];
two += b[i];
}
}
}
char[] firstPhrase = new char[one.Length];
char[] scndPhrase = new char[two.Length];
for(int i = 0; i < one.Length; i++)
{
bool temp = false;
for(int j = 0; j < two.Length; j++)
{
if(firstPhrase[j] != one[i])
{
for(int k = 0; k < scndPhrase.Length; k++)
{
if(scndPhrase[j] == two[i]) { res = true; break; }
}
if(res == true) { break; }
else { continue; }
}
if(firstPhrase[j] == one[i])
{
if (scndPhrase[j] == two[i]) { temp = true; continue; }
else { res = true; break; }
}
}
if(temp == false)
{
firstPhrase[count] = one[i];
scndPhrase[count] = two[i];
count++;
}
if(res == true) { break; }
}
if (res == true)
Console.WriteLine(res);
else
{
Console.WriteLine(!res);
for (int i = 0; i < firstPhrase.Length; i++)
{
Console.WriteLine($"{firstPhrase[i]} => {scndPhrase[i]}");
}
}
Console.Read();
}
期待您的批评,祝大家复活节快乐!
编辑:忘了提,对不起各位。测试不允许使用 LINQ 或任何其他指令,LINQ 实际上是我想尝试的第一件事。
【问题讨论】:
-
您是否可能对作业理解有误?因为它在最后说:“所以两个数组相等”并在第一个示例中将 a 替换为 t 并将 b 替换为 d 为不相等的数组提供以下内容:ttd, aab?
-
你老师有没有把这个作为第一个需要通过的测试?
-
嘿 Oguz,是的,我认为翻译中可能会丢失一些内容。即使在母语中,它的措辞也有些奇怪。您实际上不必替换字符,替换是假设的。关键是确定每个字符是否可以在另一个数组中有唯一的替换器,然后映射那些唯一的替换器。
-
不,第一个测试是使用以下输入:“ala bala portocala”和“cuc dcuc efghficuc”,并且代码通过了它。虽然没有超过第二个..
-
我赞成这两个答案,因为它们都解决了问题。我认为需要 15 个代表才能直接看到投票。