当前位置:   article > 正文

LeetCode OJ:Substring with Concatenation of All Words_given a list of words l, that are all the same len

given a list of words l, that are all the same length,andg a string, s, find

Substring with Concatenation of All Words

 

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

For example, given:
S"barfoothefoobarman"
L["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

算法思想:

暴力

  1. class Solution {
  2. public:
  3. vector<int> findSubstring(string S, vector<string> &L) {
  4. map<string, int> words;
  5. map<string, int> count;
  6. vector<int> result;
  7. int wordNum = L.size();
  8. if (wordNum == 0) return result;
  9. for (int i = 0; i < wordNum; ++i)
  10. ++words[L[i]];
  11. int wordSize = L[0].size();
  12. int slength = S.size();
  13. for (int i = 0; i <= slength - wordSize*wordNum; ++i)
  14. {
  15. count.clear();
  16. int j = 0;
  17. for (; j < wordNum; ++j)
  18. {
  19. string str = S.substr(i+j*wordSize, wordSize);
  20. if(words.find(str) == words.end())
  21. break;
  22. ++count[str];
  23. if(count[str] > words[str])
  24. break;
  25. }
  26. if (j == wordNum) result.push_back(i);
  27. }
  28. return result;
  29. }
  30. };



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

闽ICP备14008679号