|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | + |
| 6 | +namespace LeetCode_30 |
| 7 | +{ |
| 8 | + //static void Main(string[] args) |
| 9 | + //{ |
| 10 | + // var solution = new Solution(); |
| 11 | + // while (true) |
| 12 | + // { |
| 13 | + // //int input = int.Parse(Console.ReadLine()); |
| 14 | + // //int input2 = int.Parse(Console.ReadLine()); |
| 15 | + // //int input3 = int.Parse(Console.ReadLine()); |
| 16 | + // //string input = Console.ReadLine(); |
| 17 | + // //string input2 = Console.ReadLine(); |
| 18 | + // //int[] intArr = input.Split(',').Select(s => int.Parse(s)).ToArray(); |
| 19 | + // //int input2 = int.Parse(Console.ReadLine()); |
| 20 | + // //int?[] data = new int?[] { 6, 2, 8, 0, 4, 7, 9, null, null, 3, 5 }; |
| 21 | + // //int?[] data = new int?[] { 1, null, 2, 3 }; |
| 22 | + // //int?[] data = new int?[] { 1, 2, 2, 3, 3, null, null, 4, 4 }; |
| 23 | + // //int?[] data = new int?[] { 1, 2, null, 3 }; |
| 24 | + // //int?[] data = new int?[] { 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, null, null, 5, 5 }; |
| 25 | + // //var tree = new DataStructureBuilder().BuildTree(data); |
| 26 | + // //var res = solution.FindSubstring("barfoothefoobarman", new string[] { "foo", "bar" }); |
| 27 | + // //var res = solution.FindSubstring("wordgoodgoodgoodbestword", new string[] { "word", "good", "best", "word" }); |
| 28 | + // //var res = solution.FindSubstring("", new string[] { }); |
| 29 | + // var res = solution.FindSubstring("barfoofoobarthefoobarman", new string[] { "bar", "foo", "the" }); |
| 30 | + // //var res = solution.FindSubstring("pjzkrkevzztxductzzxmxsvwjkxpvukmfjywwetvfnujhweiybwvvsrfequzkhossmootkmyxgjgfordrpapjuunmqnxxdrqrfgkrsjqbszgiqlcfnrpjlcwdrvbumtotzylshdvccdmsqoadfrpsvnwpizlwszrtyclhgilklydbmfhuywotjmktnwrfvizvnmfvvqfiokkdprznnnjycttprkxpuykhmpchiksyucbmtabiqkisgbhxngmhezrrqvayfsxauampdpxtafniiwfvdufhtwajrbkxtjzqjnfocdhekumttuqwovfjrgulhekcpjszyynadxhnttgmnxkduqmmyhzfnjhducesctufqbumxbamalqudeibljgbspeotkgvddcwgxidaiqcvgwykhbysjzlzfbupkqunuqtraxrlptivshhbihtsigtpipguhbhctcvubnhqipncyxfjebdnjyetnlnvmuxhzsdahkrscewabejifmxombiamxvauuitoltyymsarqcuuoezcbqpdaprxmsrickwpgwpsoplhugbikbkotzrtqkscekkgwjycfnvwfgdzogjzjvpcvixnsqsxacfwndzvrwrycwxrcismdhqapoojegggkocyrdtkzmiekhxoppctytvphjynrhtcvxcobxbcjjivtfjiwmduhzjokkbctweqtigwfhzorjlkpuuliaipbtfldinyetoybvugevwvhhhweejogrghllsouipabfafcxnhukcbtmxzshoyyufjhzadhrelweszbfgwpkzlwxkogyogutscvuhcllphshivnoteztpxsaoaacgxyaztuixhunrowzljqfqrahosheukhahhbiaxqzfmmwcjxountkevsvpbzjnilwpoermxrtlfroqoclexxisrdhvfsindffslyekrzwzqkpeocilatftymodgztjgybtyheqgcpwogdcjlnlesefgvimwbxcbzvaibspdjnrpqtyeilkcspknyylbwndvkffmzuriilxagyerjptbgeqgebiaqnvdubrtxibhvakcyotkfonmseszhczapxdlauexehhaireihxsplgdgmxfvaevrbadbwjbdrkfbbjjkgcztkcbwagtcnrtqryuqixtzhaakjlurnumzyovawrcjiwabuwretmdamfkxrgqgcdgbrdbnugzecbgyxxdqmisaqcyjkqrntxqmdrczxbebemcblftxplafnyoxqimkhcykwamvdsxjezkpgdpvopddptdfbprjustquhlazkjfluxrzopqdstulybnqvyknrchbphcarknnhhovweaqawdyxsqsqahkepluypwrzjegqtdoxfgzdkydeoxvrfhxusrujnmjzqrrlxglcmkiykldbiasnhrjbjekystzilrwkzhontwmehrfsrzfaqrbbxncphbzuuxeteshyrveamjsfiaharkcqxefghgceeixkdgkuboupxnwhnfigpkwnqdvzlydpidcljmflbccarbiegsmweklwngvygbqpescpeichmfidgsjmkvkofvkuehsmkkbocgejoiqcnafvuokelwuqsgkyoekaroptuvekfvmtxtqshcwsztkrzwrpabqrrhnlerxjojemcxel", new string[] { "dhvf", "sind", "ffsl", "yekr", "zwzq", "kpeo", "cila", "tfty", "modg", "ztjg", "ybty", "heqg", "cpwo", "gdcj", "lnle", "sefg", "vimw", "bxcb" }); |
| 31 | + // ConsoleX.WriteLine(res); |
| 32 | + // } |
| 33 | + //} |
| 34 | + |
| 35 | + public class Solution |
| 36 | + { |
| 37 | + /// <summary> |
| 38 | + /// 滑动窗口(Sliding Window),不会退,一边进一边出,一次遍历就解决 |
| 39 | + /// s长度为n,单词个数t |
| 40 | + /// 时间复杂度:O(n) |
| 41 | + /// 空间复杂度:O(t),维护两个dictionary用于匹配 |
| 42 | + /// </summary> |
| 43 | + /// <param name="s"></param> |
| 44 | + /// <param name="words"></param> |
| 45 | + /// <returns></returns> |
| 46 | + public IList<int> FindSubstring(string s, string[] words) |
| 47 | + { |
| 48 | + IList<int> res = new List<int>(); |
| 49 | + //如果长度都小于匹配数组总长度,则一定不匹配 |
| 50 | + int tlen = words.Sum(t => t.Length); |
| 51 | + if (s == null || s.Length < tlen || words.Length == 0) |
| 52 | + return res; |
| 53 | + //单词和单词出现的频率 |
| 54 | + Dictionary<string, int> dic = new Dictionary<string, int>(); |
| 55 | + foreach (string word in words) |
| 56 | + { |
| 57 | + InsertOrAdd(dic, word); |
| 58 | + } |
| 59 | + //有一个题目上没有的隐含条件,word都是等长的 |
| 60 | + int wordLen = words[0].Length; |
| 61 | + for (int i = 0; i < wordLen; i++) |
| 62 | + { |
| 63 | + Dictionary<string, int> temp = new Dictionary<string, int>(); |
| 64 | + //其实可以不要这个参数,不过这样的话就要每次都去比对两个dictionary了,性能不好 |
| 65 | + int validWordCount = 0; |
| 66 | + for (int j = i; j + wordLen <= s.Length; j += wordLen) |
| 67 | + { |
| 68 | + //如果大于等于words总长,开始滑出(弹出一个word) |
| 69 | + if (j - i >= tlen) |
| 70 | + { |
| 71 | + string outWord = s.Substring(j - tlen, wordLen); |
| 72 | + if (dic.ContainsKey(outWord)) |
| 73 | + { |
| 74 | + validWordCount--; |
| 75 | + RemoveOrReduce(temp, outWord); |
| 76 | + } |
| 77 | + } |
| 78 | + //滑入 |
| 79 | + string inWord = s.Substring(j, wordLen); |
| 80 | + if (dic.ContainsKey(inWord)) |
| 81 | + { |
| 82 | + validWordCount++; |
| 83 | + InsertOrAdd(temp, inWord); |
| 84 | + } |
| 85 | + if (validWordCount == words.Length && CompareTwoDic(dic, temp)) |
| 86 | + res.Add(j + wordLen - tlen); |
| 87 | + } |
| 88 | + } |
| 89 | + return res; |
| 90 | + } |
| 91 | + |
| 92 | + private bool CompareTwoDic(Dictionary<string, int> dic1, Dictionary<string, int> dic2) |
| 93 | + { |
| 94 | + //Knowledge:两个dictionary的对比方法:dic1.Count == dic2.Count && !dic1.Except(dic2).Any(),key,value都会做比较。 |
| 95 | + return dic1.Count == dic2.Count && !dic1.Except(dic2).Any(); |
| 96 | + } |
| 97 | + |
| 98 | + private void InsertOrAdd(Dictionary<string, int> dic, string word) |
| 99 | + { |
| 100 | + if (!dic.ContainsKey(word)) |
| 101 | + dic.Add(word, 1); |
| 102 | + else |
| 103 | + dic[word]++; |
| 104 | + } |
| 105 | + |
| 106 | + private void RemoveOrReduce(Dictionary<string, int> dic, string word) |
| 107 | + { |
| 108 | + if (dic[word] <= 1) |
| 109 | + dic.Remove(word); |
| 110 | + else |
| 111 | + dic[word]--; |
| 112 | + } |
| 113 | + |
| 114 | + |
| 115 | + /// <summary> |
| 116 | + /// 第一反应解,算出所有组合,然后通过带匹配字符串的hash去比对。超时,算了一下组合,数量指数级上升,故不可行 |
| 117 | + /// s长度为n,words的个数为m |
| 118 | + /// 时间复杂度:O(m!),构建组合花了绝大部分时间,遍历的话只需要n,在m小的情况下这个算法是可行的 |
| 119 | + /// 空间复杂度:O(m!) |
| 120 | + /// 刚看到超时,还想用滚动hash优化一下的,debug一下结果发现是在拼接组合中就超时了 |
| 121 | + /// </summary> |
| 122 | + /// <param name="s"></param> |
| 123 | + /// <param name="words"></param> |
| 124 | + /// <returns></returns> |
| 125 | + //public IList<int> FindSubstring(string s, string[] words) |
| 126 | + //{ |
| 127 | + // IList<int> res = new List<int>(); |
| 128 | + // //如果长度都小于匹配数组总长度,则一定不匹配 |
| 129 | + // int tlen = words.Sum(t => t.Length); |
| 130 | + // if (s == null || s.Length < tlen || words.Length == 0) |
| 131 | + // return res; |
| 132 | + // //构建所有组合的字典 |
| 133 | + // RecursiveDicBuild(string.Empty, words.ToList()); |
| 134 | + // //和所有组合逐个比对hash |
| 135 | + // for (int i = 0; i <= s.Length - tlen; i++) |
| 136 | + // { |
| 137 | + // string cur = s.Substring(i, tlen); |
| 138 | + // int curHash = cur.GetHashCode(); |
| 139 | + // if (_dic.ContainsKey(curHash) && _dic[curHash] == cur) |
| 140 | + // res.Add(i); |
| 141 | + // } |
| 142 | + // return res; |
| 143 | + //} |
| 144 | + |
| 145 | + ////构建一个装所有数组匹配可能性的字典,key是组合的hashcode,string是组合内容 |
| 146 | + //private Dictionary<int, string> _dic = new Dictionary<int, string>(); |
| 147 | + //private void RecursiveDicBuild(string str, List<string> strList) |
| 148 | + //{ |
| 149 | + // if (strList == null || strList.Count == 0) |
| 150 | + // { |
| 151 | + // if (!_dic.ContainsKey(str.GetHashCode())) |
| 152 | + // _dic.Add(str.GetHashCode(), str); |
| 153 | + // } |
| 154 | + // else |
| 155 | + // { |
| 156 | + // for (int i = 0; i < strList.Count; i++) |
| 157 | + // { |
| 158 | + // string curStr = strList[i]; |
| 159 | + // var restStrList = strList.ToList(); |
| 160 | + // restStrList.RemoveAt(i); |
| 161 | + // RecursiveDicBuild(str + curStr, restStrList); |
| 162 | + // } |
| 163 | + // } |
| 164 | + //} |
| 165 | + } |
| 166 | +} |
0 commit comments