Write a function that will give the number of intersections between 2 strings. The function should take two string parameters which represents 2 words that may or may not intersect.The method should return the count of intersections which are found. For example, if the input is word 1 - Sales, word 2 - isles. The out put should be 4.
The word sales and isle intersects in 4 places.
1. The 2nd letter of isle intersects with the 1st letter of sales.
2. The 2nd letter of isle intersects with the 5th letter of sales.
3. The 3rd letter of isle intersects with the 3rd letter of sales.
4. The 4th letter of isle intersects with the 4th letter of sales.
static int numberOfIntersections(string word1, string word2)
{
if (string.IsNullOrEmpty(word1) || string.IsNullOrEmpty(word2))
return 0;
string shorterWord = string.Empty;
string longerWord = string.Empty;
//Identify the shorter word and the longer word
if (word1.Length < word2.Length)
{
shorterWord = word1.Trim();
longerWord = word2.Trim();
}
else
{
shorterWord = word2.Trim();
longerWord = word1.Trim();
}
//Create a dictionary with the characters of the shorter word
Dictionary<char, int> lookup = new Dictionary<char, int>();
Dictionary<char, int> duplicates = new Dictionary<char, int>();
foreach (char c in shorterWord)
{
if (!lookup.ContainsKey(c))
lookup.Add(c, 0);
else
{
if (!duplicates.ContainsKey(c))
duplicates.Add(c, 1);
else
duplicates[c] += 1;
}
}
//update the count of characters if the character is present in the longer word
foreach (char c in longerWord)
{
if (lookup.ContainsKey(c))
{
lookup[c] += 1;
}
}
//get the count of letters that has value greater than 0
var totalCount = lookup.Sum(l => l.Value);
int dupCount =0;
//get the letters that are common and have duplicates
foreach(KeyValuePair<char,int> d in duplicates)
{
if(lookup[d.Key] > 0)
{
dupCount += (lookup[d.Key] * duplicates[d.Key]);
}
}
return totalCount + dupCount;
}