注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
本帖最后由 wendychueng 于 2014-6-23 02:56 编辑
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).
这个是discuss里面一个人写的算法,看不太懂中间那个if... else if... else... 有没有同学可以解释一下? 谢谢!
//use hash table to store the list of words L
//for each m char in the string, check if it is a valid word
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
vector<int> result;
map<string, int> cntL;
map<string, int> cn;
int n = S.length();
int wordlen = L[0].length();
int listsize = L.size();
int count = 0; // number of words in the list
//store the list of words in hash table
for(int i=0; i<listsize; i++)
{
//if this key has not been occupied
if(cn.count(L) == 0)
{
cn[L] = 1;
count++;
}
else
{
cn[L] += 1;
count++;
}
}
string tr, du;
int r = 0;
int st = 0;
for(int j=0; j<wordlen; j++) //for each char in a word
{ r = 0; st = j;
for(int i=j; i<n; i += wordlen) //check the string for every word length substring
{
tr = S.substr(i, wordlen); //copy the next m char in the string
if(cn.count(tr) == 0 || cn[tr] == 0) //?? if this is not a valid word
{
cntL.clear();
r = 0;
st = i+wordlen;
}
else if(cntL[tr] < cn[tr]) // ???
{
cntL[tr] += 1;
r++;
}
else
{
du = S.substr(st, wordlen);
while(du != tr)
{
cntL[du]--;
r--;
st += wordlen;
du = S.substr(st, wordlen);
}
st += wordlen;
}
if(r == count) //if r == count meaning all the words have appeared
{
result.push_back(st);
du = S.substr(st, wordlen);
cntL[du]--;
r--;
st += wordlen;
}
}
cntL.clear();
}
sort(result.begin(), result.end());
return result;
}
};
|