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中的单词。L中的匹配用循环+hash计数来统计。
/* i from S
j in L
1.当j在L中匹配玩,记录
2.没匹配完,不记录
*/
class Solution {
vector<int> ret;
public:
vector<int> findSubstring(string S, vector<string> &L) {
int num = L.size();
int len = L[0].size();
//L中单词出现的次数
map<string, int> words;
for(int i = 0; i < num; i++) {
words[L[i]]++;
}
map<string, int> tmp;
for(int i = 0; i <= S.size() - num * len; i++) {
tmp.clear();
int j;
for(j = 0; j < num; j++) {
string word = S.substr(i+j*len, len);
if(words.find(word) == words.end())
break;
else
tmp[word]++;
if(tmp[word] > words[word])
break;
}
if(j == num)
ret.push_back(i);
}
return ret;
}
};
这里的代码是错误的,因为string.size()返回的是无符号数。若无符号数与有符号数作减法,是很容易溢出的。
例如:unsigned int (1) - signed int (2)
结果:若结果要转化为有符号数, 2^32 - 1; 若结果是无符号数,那么结果就是 - 1
原因:无符号数和有符号数运算时,都会被转化为无符号数
class Solution {
vector<int> ret;
public:
vector<int> findSubstring(string S, vector<string> &L) {
int num = L.size();
int width = L[0].size();
int lenS = S.size();
map<string, int> hash;
for(int i = 0; i < num; i++) {
hash[L[i]]++;
}
map<string, int> item;
for(int i = 0; i <= lenS - num * width; i++) {
item.clear();
int j;
for(j = 0; j < num; j++) {
string word = S.substr(i + j * width, width);
if(hash.find(word) == hash.end()) break;
else item[word]++;
if(item[word] > hash[word]) break;
}
if(j == num) ret.push_back(i);
}
return ret;
}
};