zoukankan      html  css  js  c++  java
  • 串联所有单词的子串

    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;
        }
    }
    
  • 相关阅读:
    Lua简介
    Using WCT
    AJAX Cntorl Toolkit ResizeableControl(可缩放控件)
    Google Maps API 1.Load Google Map
    CommandEventArgs类学习
    Windows 7 12 个使用技巧
    SQL Server 2008 不允许保存更改解决
    AJAX Control Toolkit ValidatorCallout
    硬盘整数分区最精确地算法
    Ajax Control Toolkit TabContainer
  • 原文地址:https://www.cnblogs.com/kanekiken/p/13809137.html
Copyright © 2011-2022 走看看