[leetcode]Substring with Concatenation of All Words

来源:互联网 发布:虚拟数据库 编辑:程序博客网 时间:2024/04/30 08:19

Substring with Concatenation of All Words

difficulty:hard


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).

题目给定了一个字符串s,求在s中子串的起始位置,而子串可以是给定的字符串集words中字符串不重复的组合,并且words中的字符串长度一致(假设长度为L)。

我的方法就是从头到位遍历字符串s的所有位置(当剩余的还未遍历的字符数大于子串字符数),在每一个位置上取连续的L个字符,与words中的字符串进行匹配,匹配上的话把words中匹配的字符串去掉,然后继续在s中往后取L位,继续与words中字符串进行匹配,重复以上步骤,直到不能再匹配或words为空为止,如果words为空则为匹配成功。

实际中也出现了时间复杂度过高的问题,通过使用一些技巧才符合leetcode的要求。

 vector<int> findSubstring(string s, vector<string>& words) { vector<int> result;//结果 string type;//words所有字符串的首字母 int sizeOfWords = words.at(0).size();//words中每个字符串长度 int numberOfstr = sizeOfWords*words.size();//words中所有字符串加起来的长度 也就是子串的长度 for (vector<string>::iterator it = words.begin(); it != words.end(); it++){//把words中所有字符串的首字母合在一起 方便查询 type.append(it->substr(0, 1)); } for (int i = 0; i < s.size(); i++){//遍历s string tmp; if (s.size() - i >= numberOfstr)//剩余的字符串大于子串的长度 tmp = s.substr(i, 1); else break; vector<string> tmp_words = words; if (type.find(tmp) != string::npos){//当前遍历的字符是words某一字符串的首字母 tmp = s.substr(i, sizeOfWords);//读取sizeOfWords长度的字符串 for (vector<string>::iterator it2 = tmp_words.begin(); it2 != tmp_words.end(); it2++){//试图把读取的字符串与tmp_words中的字符串进行匹配并从中去掉 if (*it2 == tmp){ tmp_words.erase(it2); break; } } if (tmp_words.size() == words.size())//如果没有去掉即为没有匹配 continue; int m = i + sizeOfWords; bool isNext = true; while (isNext){//继续向下读取sizeOfWords个字符并与tmp_words中的字符串进行匹配并从中去掉 isNext = false; string match; if (s.size() >= m + sizeOfWords)//判断是否有读取越界 match = s.substr(m, sizeOfWords); else break; for (vector<string>::iterator it3 = tmp_words.begin(); it3 != tmp_words.end(); it3++){ if (match == *it3){ tmp_words.erase(it3); m = m + sizeOfWords; isNext = true; break; } } } if (tmp_words.size() == 0){//tmp_words为空 说明成功匹配 result.push_back(i); } } } return result; }


0 0
原创粉丝点击