您的位置:首页 > 其它

030 - Substring with Concatenation of All Words

2015-11-11 18:39 337 查看
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in
s that is a concatenation of each word in words exactly once and without any intervening characters.

For example, given:
s:
"barfoothefoobarman"

words:
["foo", "bar"]


You should return the indices:
[0,9]
.

(order does not matter).

这题目我也晕了,给定一个字符串,另外一组关键字,在字符串中找到所有这些关键字级联起来的串的起始位置,这些关键字可以随意顺序

这个问题处理起来很纠结,以后在寻找更简单的解决方法

/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/

void fun(char* start, char* s, char** words, int wordsSize, int *mark, int *ret, int* returnSize)
{
int marksize = 0;
int wlen = strlen(words[0]);
int wordstr = wlen * wordsSize;
int remain = wordsSize;
int i;
while (strlen(s) >= wordstr) {
char *move = s + marksize * wlen;
//remain = wordsSize - marksize;
while (remain) {
for (i = 0;i < wordsSize; i++) {
if (mark[i]) continue;
if (!strncmp(words[i], move, wlen)) {
mark[i] = 1;
marksize++;
remain--;
break;
}
}
if (i >= wordsSize) break;
move += wlen;
}
if (!remain) {
ret[(*returnSize)++] = s - start;
}
for (i = 0; i < wordsSize; i++) {
if (!strncmp(words[i], s, wlen)) {
mark[i] = 0;
remain++;
marksize--;
break;
}
}
for (i = 0; i < wordsSize; i++) mark[i] = 0;
s += 1;
remain = wordsSize;
marksize = 0;
}
}
int* findSubstring(char* s, char** words, int wordsSize, int* returnSize)
{
*returnSize = 0;
int *mark = (int *)calloc(sizeof(int), wordsSize);
int *ret = (int *)calloc(sizeof(int), 8192);
fun(s, s, words, wordsSize, mark, ret, returnSize);
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: