leetcode-30-Substring with Concatenation of All Words

来源:互联网 发布:怎么找淘宝内购优惠券 编辑:程序博客网 时间:2024/06/06 05:03

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

题目大意:
s是str,words是包含若干个str的list。找到s中的所有位置,从这些位置开始往后可以包括words中所有str。包含的顺序无关,但是要次数相同。比如在words中有出现3次的字符串要同样在该位置后一段距离出现3次。

思路:
遍历words。用字典哈希表保存words中每一个元素出现的次数。
遍历s。到达每一个位置后,每次往后截取一个word长度的元素保存在temp中,判断temp是否在map里。维护一个临时tmpmap保存每个s的位置往后出现的words中元素的次数。维护一个break条件flag。
当某次截取的temp不在map里,flag为false,break。
当某word在tmpmap中次数大于map中次数,flag置false,break。

开始想的是每次遍历s的某一位置都copy一个words,然后截取一个word,在words中就在words中将该元素删除。知道某个word不在words中或者words为空时退出。思路简洁没问题。
结果超时。words元素多了以后时间复杂度巨大。要遍历s长度次words。
用字典只需要遍历一次words。

python代码:

class Solution(object):    def findSubstring(self, s, words):        """        :type s: str        :type words: List[str]        :rtype: List[int]        """        lens=len(s)        lenw=len(words)        len0=len(words[0])        map={}        res=[]        for i in words:            if i in map:map[i]+=1            else:map[i]=1         for i in range(lens-lenw*len0+1):            tmpmap={}            for j in range(lenw):                flag=True                k=i+j*len0                temp=s[k:k+len0]                if temp in map:                    num=0                    if temp in tmpmap:num=tmpmap[temp]                    if map[temp]<num+1:flag=False;break                    tmpmap[temp]=num+1                else:                     flag=False                    break            if flag:res.append(i)        return res

AC。700+ms。

c++代码:
也要700+ms。思路一样。
不知道结果里面100以内怎么做到的。。

class Solution {public:    vector<int> findSubstring(string S, vector<string> &L) {        map<string, int> words;        map<string, int> curWords;        vector<int> ret;        int slen = S.length();        if (!slen || L.empty()) return ret;        int llen = L.size(), wlen = L[0].length();        // record the current words map        for (auto &i : L)            ++words[i];        // check the [llen * wlen] substring        for (int i = 0; i + llen * wlen <= slen; i++) {            curWords.clear();            int j = 0;            // check the words            for (j = 0; j < llen; j++) {                string tmp = S.substr(i + j * wlen, wlen);                if (words.find(tmp) == words.end())                    break;                ++curWords[tmp];                if (curWords[tmp] > words[tmp])                    break;            }            if (j == llen)                ret.push_back(i);        }        return ret;    }};
0 0