'Determine which words are anagrams of each other - Hackerrank latest question
I got below question from Hackerrank but i haven't able to solve it getting some issue in dictionary below is my code in which i got error while running . could you please check and let me know where i messed up
Question
Given an array of words and an array of sentences, determine which words are anagrams of each other. Calculate how many sentences can be created by replacing any word with one of the anagrams.
Example wordSet = ['listen', 'silent, 'it', 'is'] sentence = 'listen it is silent' Determine that listen is an anagram of silent. Those two words can be replaced with their anagrams.
The four sentences that can be created are:
• listen it is silent • listen it is listen • silent it is silent • silent it is listen
Function Description Complete the countSentences function in the editor below. countSentences has the following parameters: string wordSet[n]: an array of strings string sentences[m]: an array of strings Returns: int[]: an array of m integers that denote the number of sentences that can be formed from each sentence
Below is the code that i tried in c#( Working solution is avaliable in JAVA which i used as reference to make the code in C#.
Java Working code ref link https://leetcode.com/playground/dBCY7Rs4
static void Main(string[] args) {
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] + " ");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
