【发布时间】:2022-01-23 16:19:57
【问题描述】:
对于给定的单词,计算可能的字谜的数量。 结果词不必存在于字典中。 字谜不必重复,也不必生成字谜,只需计算它们的数量。
最后一个测试不工作,我不知道我应该如何让它工作。你能帮帮我吗?
这是我的代码:
using System;
static void Main(string[] args)
{
string word = Console.ReadLine();
int wordLenth = word.Length;
int sameLetter = 1;
for (int i=0;i<wordLenth;i++)
{
for (int j=i+1;j<wordLenth;j++)
{
if (word[i]==word[j])
{
sameLetter++;
}
}
}
int firstResult=1, secondResult=1, lastResult;
for (int i=1; i <= wordLenth; i++)
{
firstResult *= i;
}
for (int i = 1; i <= sameLetter; i++)
{
secondResult *= i;
}
lastResult = firstResult / secondResult;
Console.WriteLine(lastResult);
}
Results:
Compilation successfully executed.
Test 1: Correctly calculate the number of anagrams for "abc" - successful
Test 2: Correctly calculate the number of anagrams for "abc" - success
Test 3: Correctly calculates the number of anagrams for "aaab" - failed
Expected results: "4"
Results obtained: "1"
如果有重复的字母,提交的解决方案不会正确计算唯一字谜的数量。
【问题讨论】:
-
您的解决方案行不通,因为您只检查了一次
sameLetter,但是如果您有两个或多个重复的字母怎么办,例如“aaabbbcccdddd”? -
你也可以用一些数学来解决这个问题,例如math.stackexchange.com/questions/114654/…
标签: c# arrays string algorithm anagram