Saturday, August 25, 2018

Sherlock and Anagrams

Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
For example , the list of all anagrammatic pairs is  at positions  respectively.
Function Description
Complete the function sherlockAndAnagrams in the editor below. It must return an integer that represents the number of anagrammatic pairs of substrings in .
sherlockAndAnagrams has the following parameter(s):
  • s: a string .
Input Format
The first line contains an integer , the number of queries.
Each of the next  lines contains a string  to analyze.
Constraints


String  contains only lowercase letters  ascii[a-z].
Output Format
For each query, return the number of unordered anagrammatic pairs.
Solution :- 

  static int sherlockAndAnagrams(string s)
        {            
            int count = 0;
            var dictStr = new Dictionary<string, int>();
            for (int i = 0; i < s.Length; i++)
            {
                for (int j=i+1; j <= s.Length; j++)
                {
                    var str = s.Substring(i, j-i);
                    var chars = str.ToCharArray();
                    Array.Sort(chars);
                    var word = new string(chars);
                    if (dictStr.ContainsKey(word))
                    {
                        var value = dictStr[word];
                        count = count + value;
                        dictStr[word] = value + 1;
                    }
                    else
                        dictStr.Add(word, 1);                    
                }
            }
            return count;
        }


No comments:

Post a Comment

Kafka setup in window

Here's a step-by-step guide on how to do it : 1. Prerequisites : Before you begin, make sure you have the following prerequisites inst...