c# solution


  • 0
    C
    public IList<int> FindAnagrams(string str, string pat)
    {
        var result = new List<int>();
        var pattern = new Dictionary<char, int>();
        var window = new Dictionary<char, int>();
    
        foreach (char p in pat)
        {
            if (!pattern.ContainsKey(p))
                pattern.Add(p, 1);
            else
                pattern[p]++;
        }
    
        for (int i = 0, j = 0; j < str.Length; ++j)
        {
            char s = str[j];
    
            if (!window.ContainsKey(s))
                window.Add(s, 1);
            else
                window[s]++;
    
            if (j - i + 1 == pat.Length)
            {
                if (pattern.Count == window.Count)
                {
                    int count = pat.Length;
    
                    foreach (char p in pattern.Keys)
                    {
                        if (!window.ContainsKey(p) ||
                            window[p] != pattern[p])
                        {
                            break;
                        }
    
                        count -= pattern[p];
                    }
    
                    if (count == 0)
                        result.Add(i);
                }
    
                char first_in_window = str[i];
                if (--window[first_in_window] == 0)
                    window.Remove(first_in_window);
    
                i++;
            }
        }
    
        return result;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.