当前位置:   article > 正文

Leetcode: Substring with Concatenation of All Words

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).

一开始理解错题意了,以为只要有L中的单词在S中没有干扰词汇的连续出现就要记下来呢,提交发现不对,人家是each word in L exactly once.是要所有L中的词都出现一遍,中间不能有其他的干扰词汇。并且L中的词也会有重复。

错误代码:

  1. vector<int> findSubstring(string S, vector<string> &L) {
  2. // Note: The Solution object is instantiated only once.
  3. set<string> dic;
  4. for(int i = 0; i < L.size(); i++)
  5. dic.insert(L[i]);
  6. vector<int> res;
  7. int wordlen = L[0].size();
  8. set<string>::iterator it;
  9. int i = 0;
  10. bool isLastOk = false;
  11. while(i < S.size())
  12. {
  13. string sub = S.substr(i,wordlen);
  14. it = dic.find(sub);
  15. if(it != dic.end())
  16. {
  17. if(!isLastOk)
  18. {
  19. res.push_back(i);
  20. isLastOk = true;
  21. }
  22. i += wordlen;
  23. }else
  24. {
  25. isLastOk = false;
  26. i++;
  27. }
  28. }
  29. return res;
  30. }

正确代码如下:

  1. vector<int> findSubstring(string S, vector<string> &L) {
  2. // Note: The Solution object is instantiated only once.
  3. map<string,int> words;
  4. map<string,int> cur;
  5. int wordNum = L.size();
  6. for(int i = 0; i < wordNum; i++)
  7. words[L[i]]++;
  8. int wordLen = L[0].size();
  9. vector<int> res;
  10. //if(S.size() < wordLen*wordNum)return res;
  11. for(int i = 0; i <= (int)S.size()-wordLen*wordNum; i++)
  12. {
  13. cur.clear();
  14. int j;
  15. for(j = 0; j < wordNum; j++)
  16. {
  17. string word = S.substr(i+j*wordLen, wordLen);
  18. if(words.find(word) == words.end())
  19. break;
  20. cur[word]++;
  21. if(cur[word]>words[word])
  22. break;
  23. }
  24. if(j == wordNum)
  25. res.push_back(i);
  26. }
  27. return res;
  28. }




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

闽ICP备14008679号