leetcode 30 -- Substring with Concatenation of All Words

Substring with Concatenation of All Words

题目:
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,和另外一个字符串数组a,组合a中所有字符串为一个新串,找新串在s中出现的所有位置,并返回一个数组。

思路:
用hash的思想,先将数组中的字符串(长度全部相等)全部放到hash表中(我用的map),需要注意的一点就是数组中字符串可能出现不止一次,会重复,所以我们给hash表存的值累加,记录出现次数。然后不断的截取给定字符串s的子串,分割成的子串也放进临时的新的hash表,比较两个hash表。

代码:

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        map<string, int>mp;
        map<string, int>cur;
        vector<int>ret;
        //初始化map
        for(auto iter = words.begin(); iter != words.end(); ++iter){
            mp[*iter]++;
        }

        size_t size = words.size();
        //length和size返回的都是size_t
        int len = (int)(size*words[0].length());
        int num = (int)(s.length()-len);
        //轮寻s
        for(int i = 0; i <= num; ++i){
            cur.clear();
            //截取长度和数组组成的串相同的字串
            string subs = s.substr(i, len);
            int j = 0;
            //建立新map,并且和原map比较。
            for(j = 0; j < size; ++j){
                string curstr = subs.substr(j*words[0].length(), words[0].length());
                auto iter2 = mp.find(curstr);
                //没找到相应string,break
                if(iter2 == mp.end()){
                    break;
                }
                cur[curstr]++;
                //出现次数多,break
                if(cur[curstr] > mp[curstr]){
                    break;
                }
            }
            //成功结束循环说明满足条件,添加到返回的vector
            if(j == size){
                ret.push_back(i);
            }
        }
        return ret;
    }
};

注意:
以后看清题在做,这道题开始理解错题意,也没注意到数组会有重复出现的字符串,所以浪费比较多的时间。

你可能感兴趣的:(String,list,find,substring)