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;
        }
    }
    
  • 相关阅读:
    再探最大公约数
    非旋treap
    初赛毒瘤汇总(持续更新中)
    架构漫谈阅读笔记五--以豆瓣得基础架构为例
    架构设计小论文
    第一阶段
    架构漫谈阅读笔记六--以淘宝数据魔方技术架构解析为例
    学习进度第八周
    架构漫谈阅读笔记一
    软件架构之 Refined Architecture阶段
  • 原文地址:https://www.cnblogs.com/kanekiken/p/13809137.html
Copyright © 2011-2022 走看看