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:
L:
You should return the indices:
(order does not matter).
--O(n) not optimized
*/For example, given:
S:
"barfoothefoobarman"L:
["foo", "bar"] You should return the indices:
[0,9].(order does not matter).
--O(n) not optimized
class Solution {
public:
vector<string>::iterator findWord(vector<string> L, string input){
vector<string>::iterator it;
for(it=L.begin();it<L.end();it++){
if(*it==input){
return it;
}
}
return L.end();
}
vector<int> findSubstring(string S, vector<string> &L) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> result;
int numOfWord = L.size();
if(numOfWord==0) return result;
int wordSize = L.at(0).length();
int pos = 0;
int size = S.length();
int currStart;
vector<string>::iterator found;
vector<string> temp;
bool wordExist = false;
while(pos<size-numOfWord*wordSize+1){
temp.clear();
temp.insert(temp.begin(),L.begin(),L.end());
currStart = pos;
while(temp.size()!=0 && currStart<size-wordSize+1){
//found = findWord(L, S.substr(currStart,wordSize));
wordExist = false;
for(found=temp.begin();found<temp.end();found++){
if(found!=temp.end()&&*found==S.substr(currStart,wordSize)){
temp.erase(found);
wordExist = true;
break;
}
}
if(wordExist){
currStart = currStart+wordSize;
}
else break;
}
if(temp.size()==0){
result.push_back(pos);
}
pos++;
}
return result;
}
};
No comments:
Post a Comment