串联所有单词的子串

30. 串联所有单词的子串

方法:滑动窗口 哈希表

关键技巧点:长度相同的单词。== 比如单词的长度为3,则0,3,6..1,4,7..2,5,8..一定能覆盖所有的拆分字符串。
思路:维护word和缓存的查找哈希表。当两个哈希表数值正常的时候,即找到一个结果。

public class Solution
{
    public IList<int> FindSubstring(string s, string[] words)
    {
        IList<int> res = new List<int>();
        if (String.IsNullOrEmpty(s) || s.Length == 0 || words == null || words.Length == 0) return res;
        Dictionary<string, int> map = new Dictionary<string, int>();
        int oneWord = words[0].Length;
        int wordNum = words.Length;
        foreach (var word in words)
        {
            if (map.ContainsKey(word))
            {
                map[word] += 1;
            }
            else
            {
                map[word] = 1;
            }
        }

        for (int i = 0; i < oneWord; i++)
        {
            int left = i, right = i, count = 0;
            Dictionary<string, int> tmpDict = new Dictionary<string, int>();
            while (right + oneWord <= s.Length)
            {
                string w = s.Substring(right, oneWord);
                right += oneWord;
                if (!map.ContainsKey(w))
                {
                    count = 0;
                    left = right;
                    tmpDict.Clear();
                }
                else
                {
                    if (tmpDict.ContainsKey(w))
                    {
                        tmpDict[w] += 1;
                    }
                    else
                    {
                        tmpDict.Add(w, 1);
                    }

                    count++;
                    while ((tmpDict.ContainsKey(w) ? tmpDict[w] : 0) > (map.ContainsKey(w) ? map[w] : 0))
                    {
                        string tmpW = s.Substring(left, oneWord);
                        count--;
                        if (tmpDict.ContainsKey(tmpW))
                        {
                            tmpDict[tmpW] -= 1;
                        }

                        left += oneWord;
                    }

                    if (count == wordNum)
                    {
                        res.Add(left);
                    }
                }
            }
        }

        return res;
    }
}
posted @ 2020-10-13 15:28  Quintinz  阅读(171)  评论(0编辑  收藏  举报