【LeetCode算法练习(C++)】Substring with Concatenation of All Words

来源:互联网 发布:曼隆学院 知乎 编辑:程序博客网 时间:2024/05/21 06:21

题目:
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).

链接:Substring with Concatenation of All Words
解法:枚举子串,切分后用map判断。时间O(n*m)

class Solution {public:    vector<int> findSubstring(string s, vector<string>& words) {        map<string, int> mwords;        map<string, int> curWords;        vector<int> ret;        int slen = s.length();        if (!slen || words.empty()) return ret;        int llen = words.size(), wlen = words[0].length();        for (vector<string>::iterator i = words.begin(); i != words.end(); i++) mwords[*i]++;        for (int i = 0; i + llen * wlen <= slen; i++) {            curWords.clear();            int j = 0;            for (j = 0; j < llen; j++) {                string tmp = s.substr(i + j * wlen, wlen);                if (mwords.find(tmp) == mwords.end())                    break;                ++curWords[tmp];                if (curWords[tmp] > mwords[tmp])                    break;            }            if (j == llen) ret.push_back(i);        }        return ret;    };};

Runtime: 152 ms

阅读全文
0 0