您的位置:首页 > 其它

LeetCode: Substring with Concatenation of All Words

2014-08-28 22:09 363 查看
思路:就是找出L中所有字符串的全排列组成一个新的字符串,看是否在S中,因为全排列是n!级的,当然不能排好一一去找,可以利用map这一数据结构,将L每个字符串计数,然后再在S中选择一个开始位置i,将后续的子串S(i,L.size() * word_size)切成L.size()个字符串组(字符串长度相等简化了这一问题),看是否在前面的map结构中出现,而且也计数,如果数目不等或者没有在前面的map出现,都说明当前位置i开始的子串不符合条件。

code:

class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
vector<int> ret;
map<string,int> L_count,S_count;
for(int i = 0;i < L.size();i++)
L_count[L[i]]++;

int len = L[0].length();
int s_len = S.length();
int l_len = L.size();
int j;
for(int i = 0;i <= s_len - l_len * len;i++){
S_count.clear();
for(j = 0;j < l_len;j++){
string leftStr = S.substr(i+j*len,len);
if(L_count.find(leftStr) != L_count.end()){
S_count[leftStr]++;
if(S_count[leftStr] > L_count[leftStr])
break;
}
else
break;
}
if(j == l_len)
ret.push_back(i);
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: