我从Hackerrank下面的问题,但我还没有能够解决它得到一些问题,在字典下面是我的代码,我得到了错误,而运行。你能帮我查一下,让我知道我哪里出错了吗?
问题
给定一个单词数组和一个句子数组,确定哪些单词是彼此的字谜。计算有多少句子可以通过替换任何一个单词的字谜。
示例wordSet ='listen ','silent,'it','is'] sentence = 'listen it is silent'确定listen是silent的变位词。这两个词可以用它们的字谜来代替。
可以创建的四句话是:
·听它是无声的·听它是无声的·听它是无声的·听它是无声的
函数描述在下面的编辑器中完成countSentences函数。countSentences具有以下参数:string wordSet[n]:一个字符串数组string sentences[m]:一个字符串数组返回:int[]:一个m个整数的数组,表示每个句子可以组成的句子数量
下面是我在C#中尝试的代码(工作解决方案在JAVA中可用,我用它作为参考来编写C#中的代码。
Java Working code ref link https://leetcode.com/playground/dBCY7Rs4
public boolean canCatchTheft(int [] nums){
String[] arr
= { "cat", "dog", "tac", "god", "act" };
printAnagrams(arr);
String[] words = { "bats", "tabs", "in", "cat", "act" };
String[] sentences = { "cat the bats", "in the act", "act tabs in" };
int[] count = new int[1000];
Dictionary<String, List<String>> map = new Dictionary<String, List<String>>();
Dictionary<String, List<String>> mapToUse = new Dictionary<String, List<String>>();
foreach (string word in words)
{
char[] charArr = word.ToCharArray();
Array.Sort(charArr);
String sorted = new String(charArr);
if (map.ContainsKey(sorted))
{
//
List<String> list = map[sorted];
list.Add(word);
map.Add(sorted, list);
mapToUse.Add(word, list);
}
else
{
//
List<String> list = new List<String>();
list.Add(word);
map.Add(sorted, list);
mapToUse.Add(word, list);
}
}
int index = 0;
foreach (String sentence in sentences)
{
int c = 1;
String[] strArr = sentence.Trim().Split(' ');
foreach (String str in strArr)
{
if (mapToUse.ContainsKey(str))
{
List<String> list = mapToUse[str];
c = c * list.Count();
}
}
count[index++] = c;
}
for (int i = 0; i < count.Length; i++)
{
Console.WriteLine(count[i] + " ");
}
}
1条答案
按热度按时间bwleehnv1#
HackerRank认证最重要的问题是字符串变位,我提供的是python中的解决方案-3我希望下面的变位代码对很多人破解hackerRank字符串变位考试有用。