赞
踩
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).
暴力
- class Solution {
- public:
- vector<int> findSubstring(string S, vector<string> &L) {
-
- map<string, int> words;
- map<string, int> count;
- vector<int> result;
- int wordNum = L.size();
- if (wordNum == 0) return result;
- for (int i = 0; i < wordNum; ++i)
- ++words[L[i]];
-
- int wordSize = L[0].size();
- int slength = S.size();
- for (int i = 0; i <= slength - wordSize*wordNum; ++i)
- {
- count.clear();
- int j = 0;
- for (; j < wordNum; ++j)
- {
- string str = S.substr(i+j*wordSize, wordSize);
- if(words.find(str) == words.end())
- break;
- ++count[str];
- if(count[str] > words[str])
- break;
- }
- if (j == wordNum) result.push_back(i);
- }
- return result;
- }
- };

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。