Find All Occurrences of a String in a String Using Sliding Window Technique
"class Solution {\n List<int> findSubstring(String s, List<String> words) {\n var map = <String, int>{};\n for (String word in words) {\n map.putIfAbsent(word, () => map.length);\n }\n var counts = List<int>.filled(map.length, 0);\n for (String word in words) {\n counts[map[word]!]++;\n }\n var res = <int>[];\n int sLen = s.length;\n int wordNum = words.length;\n int wordLen = words[0].length;\n int len = wordLen * wordNum;\n for (int i = 0; i < wordLen; i++) {\n for (int j = i; j <= sLen - len; j += wordLen) {\n var windows = List<int>.filled(map.length, 0);\n for (int k = wordNum - 1; k >= 0; k--) {\n int begin = j + k * wordLen;\n String word = s.substring(begin, begin + wordLen);\n int index = -1;\n if (map[word] != null) {\n index = map[word]!;\n }\n if (index == -1 || windows[index]++ == counts[index]) {\n j = begin;\n break;\n }\n if (k == 0) {\n res.add(j);\n }\n }\n }\n }\n return res;\n }\n}//转换成C++内容:#include <iostream>\n#include <vector>\n#include <unordered_map>\n\nusing namespace std;\n\nvector<int> findSubstring(string s, vector<string>& words) {\n unordered_map<string, int> map;\n for (string word : words) {\n map[word] = map.size();\n }\n vector<int> counts(map.size(), 0);\n for (string word : words) {\n counts[map[word]]++;\n }\n vector<int> res;\n int sLen = s.size();\n int wordNum = words.size();\n int wordLen = words[0].size();\n int len = wordLen * wordNum;\n for (int i = 0; i < wordLen; i++) {\n for (int j = i; j <= sLen - len; j += wordLen) {\n vector<int> windows(map.size(), 0);\n for (int k = wordNum - 1; k >= 0; k--) {\n int begin = j + k * wordLen;\n string word = s.substr(begin, wordLen);\n int index = -1;\n if (map.count(word) > 0) {\n index = map[word];\n }\n if (index == -1 || windows[index]++ == counts[index]) {\n j = begin;\n break;\n }\n if (k == 0) {\n res.push_back(j);\n }\n }\n }\n }\n return res;\n}\n\nint main() {\n string s = "barfoothefoobarman";\n vector<string> words = {"foo", "bar";\n vector<int> result = findSubstring(s, words);\n for (int num : result) {\n cout << num << " " ;\n }\n cout << endl;\n return 0;\n}\n
原文地址: https://www.cveoy.top/t/topic/qjLP 著作权归作者所有。请勿转载和采集!