zoukankan      html  css  js  c++  java
  • Substring with Concatenation of All Words

    You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

    For example, given:
    S"barfoothefoobarman"
    L["foo", "bar"]

    You should return the indices: [0,9].
    (order does not matter).

    class Solution {
    public:
        vector<int> findSubstring(string S, vector<string> &L) 
        {        
            vector<int> ret;
            int lsize=L.size();
            if(lsize==0return ret;

            int slen=S.length();
            int wordlen=L[0].length();
            
            map<string,int> lmap;
            for(int i=0;i<lsize;i++)
                if(lmap.find(L[i])==lmap.end())
                    lmap[L[i]]=1;
                else
                    lmap[L[i]]++;

            for(int i=0;i<slen-lsize*wordlen+1;i++)
            {        
                map<string,int> imap;
                bool valid=true;
                for(int j=0;j<lsize;j++)
                {
                    int start=i+j*wordlen;
                    string word=S.substr(start,wordlen);
                    imap[word]++;
                    if(lmap.find(word)==lmap.end() || lmap[word]<imap[word])
                    {
                        valid=false;
                        break;
                    }
                    
                }
                if(!valid) continue;
                else
                    ret.push_back(i);
            }
            return ret;
        }
    }; 
  • 相关阅读:
    Curling 2.0
    POJ
    免费馅饼
    每日一九度之 题目1090:路径打印
    每日一九度之 题目1089:数字反转
    每日一九度之 题目1084:整数拆分
    每日一九度之 题目1083:特殊乘法
    每日一九度之 题目1081:递推数列
    每日一九度之 题目1079:手机键盘
    每日一九度之 题目1077:最大序列和
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759315.html
Copyright © 2011-2022 走看看