Substring with Concatenation of All Words--LeetCode

来源:互联网 发布:女网球运动服知乎 编辑:程序博客网 时间:2024/06/05 18:09

1.题目

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

2.题意

不额外插入字符,找出串联列表中所有单词的子串的起始位置
每个单词的长度相同

3.分析

借助两个哈希表
m1记录所有单词出现的次数
每次找出给定单词长度的子串,看其是否在m1里
如果不存在,立即break
如果有,则加入m2,如果该单词在m2中出现次数更多,也break
如果正好匹配完words里所有的单词,则i存入result

一定要注意两个点
i<=(int)s.size()-m*n中的==号不要遗漏,s.size()要类型转换
int j=0;放在循环外,否则得到的结果为空

4.代码

class Solution {public:    vector<int> findSubstring(string s, vector<string>& words) {        vector<int> result;        int len = s.size();        int m = words.size();        if(len == 0 || m == 0)            return result;        unordered_map<string, int> m1;        for(auto &tmp : words)            ++m1[tmp];        int n = words[0].size();        for(int i = 0; i <= len - m * n; ++i)        {            unordered_map<string, int> m2;            int j = 0;            for(j = 0; j < m; ++j)            {                string tmp = s.substr(i + j * n, n);                if(m1.find(tmp) == m1.end())                    break;                ++m2[tmp];                if(m2[tmp] > m1[tmp])                    break;            }            if(j == m)                result.push_back(i);        }        return result;    }};
原创粉丝点击