zoukankan      html  css  js  c++  java
  • [LeetCode] #30 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 wordsexactly 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).

    本题是寻找字符串中子串集出现的位置,先对子串集做成字典,然后依次匹配。时间:568ms,代码如下:

    class Solution {
    public:
        vector<int> findSubstring(string s, vector<string>& words) {
            vector<int> res;
            if (s.empty() || words.empty() || s.size() < words.size()*words[0].size())
                return res;
            int  searchEnd = s.size() - words.size() * words[0].size();
            size_t wordLen = words[0].size(), wordNum = words.size();
            map<string, int> total, submap;
            for (size_t i = 0; i < wordNum; ++i)
                total[words[i]]++;
            for (size_t i = 0; i <= searchEnd; ++i){
                submap.clear();
                size_t k = 0;
                for (size_t j = i; k < wordNum; j += wordLen, ++k){
                    string str = s.substr(j, wordLen);
                    if (total.find(str) == total.end())
                        break;
                    else if (++submap[str]>total[str])
                        break;
                }
                if (k == words.size())
                    res.push_back(i);
            }
            return res;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    [php-src]一个Php扩展的结构
    告别2015,迎来2016
    [JS]应用splice删除多元素时出现的坑
    [Ng]Angular应用点概览
    [MongoDB]Mongodb攻略
    GNU M4
    [Linux]服务管理:RPM包, 源码包
    [Shell]条件判断与流程控制:if, case, for, while, until
    [Shell]字符截取命令:cut, printf, awk, sed
    [Shell]正则表达式与通配符
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4575712.html
Copyright © 2011-2022 走看看