当前位置:   article > 正文

LeetCode算法系列:30. Substring with Concatenation of All Words

substring with concatenation of all words

题目描述

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Input:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.

Example 2:

Input:
  s = "wordgoodstudentgoodword",
  words = ["word","student"]
Output: []

算法实现:

  1. class Solution {
  2. public:
  3. vector<int> findSubstring(string s, vector<string>& words) {
  4. vector<int> res;
  5. if(s.empty()) return res;
  6. if(words.empty()) return res;
  7. unordered_map<string, int> m;
  8. unordered_map<string, int> mt;
  9. int word_nums = words.size();
  10. int word_size = words[0].length();
  11. for(int i = 0; i < words.size(); i ++)m[words[i]] ++;
  12. int j;
  13. for(int i = 0; i < s.length(); i ++){
  14. mt.clear();
  15. for(j = 0; j < word_nums; j ++)
  16. {
  17. string word = s.substr(i + j*word_size, word_size);
  18. if(m.count(word))
  19. {
  20. if(mt[word] < m[word])mt[word] ++;
  21. else break;
  22. }
  23. else break;
  24. }
  25. if(j == word_nums) res.push_back(i);
  26. }
  27. return res;
  28. }
  29. };

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/252581
推荐阅读
相关标签
  

闽ICP备14008679号