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.”
  • 相关阅读:
    MFC子窗体、父窗体
    私有云计算安全问题不容忽视
    云计算更多的是一种模式而不是技术
    原型模式向量的原型
    企业发票异常分析分离进项与销项
    考试系统框架搭建
    抽象工厂模式人与肤色
    工厂方法模式加密算法
    简单工厂模式女娲造人
    企业发票异常分析导入,清洗
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4575712.html
Copyright © 2011-2022 走看看