LeetCode Substring with Concatenation of All Words

来源:互联网 发布:云计算数据中心 用电 编辑:程序博客网 时间:2024/06/10 20:30

问题网址:https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/

问题描述:
给你一个字符串s和一个长度相同的单词列表。 找出s中所有子字符串的起始索引,这些字符串中的每个单词只是一个字符串,没有任何中介字符。

例如,给出:
s:“barfoothefoobarman”
词语:[“foo”,“bar”]

你应该返回索引:[0,9]。
(顺序无关紧要)。

一个O(N)的解法

 // travel all the words combinations to maintain a window    // there are wl(word len) times travel    // each time, n/wl words, mostly 2 times travel for each word    // one left side of the window, the other right side of the window    // so, time complexity O(wl * 2 * N/wl) = O(2N)    vector<int> findSubstring(string S, vector<string> &L) {        vector<int> ans;        int n = S.size(), cnt = L.size();        if (n <= 0 || cnt <= 0) return ans;        // init word occurence        unordered_map<string, int> dict;        for (int i = 0; i < cnt; ++i) dict[L[i]]++;        // travel all sub string combinations        int wl = L[0].size();        for (int i = 0; i < wl; ++i) {            int left = i, count = 0;            unordered_map<string, int> tdict;            for (int j = i; j <= n - wl; j += wl) {                string str = S.substr(j, wl);                // a valid word, accumulate results                if (dict.count(str)) {                    tdict[str]++;                    if (tdict[str] <= dict[str])                         count++;                    else {                        // a more word, advance the window left side possiablly                        while (tdict[str] > dict[str]) {                            string str1 = S.substr(left, wl);                            tdict[str1]--;                            if (tdict[str1] < dict[str1]) count--;                            left += wl;                        }                    }                    // come to a result                    if (count == cnt) {                        ans.push_back(left);                        // advance one word                        tdict[S.substr(left, wl)]--;                        count--;                        left += wl;                    }                }                // not a valid word, reset all vars                else {                    tdict.clear();                    count = 0;                    left = j + wl;                }            }        }        return ans;    }
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 越前菜菜子 前菜 西餐前菜菜谱 前蜀 后唐灭前蜀之战 蜀都 蜀中 蜀都中心 前束角 前角 外侧半月板前角撕裂 半月板前角损伤用什么方法好 半月板前角变性 脊髓前角运动神经元 半月板前角 半月板前角损伤人工置换 半月板前角退变 左膝关节外侧半月板前角损伤 前言 前言怎么写 画展前言 展览前言 前言不搭后语 工作总结前言佳句 项目策划书前言 职业规划前言怎么写 同学通讯录前言 职业规划的前言 职业规划前言范文 如何写论文前言 论文的前言主要写什么 功德碑前言怎么写 通用前言范文 朝花夕拾前言 职业生涯规划前言怎么写 暑期社会实践前言 职业生涯规划前言300 职业生涯规划书前言 大学生职业生涯规划前言 书法美术摄影展前言