zoukankan      html  css  js  c++  java
  • 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).

    思路:

    定义两个hash表,一个就是传统的把所有的输入进去,对应代号。

    本题的一个技巧就是每次从一个位置开始判断,然后再最外面写一个从当前位置判断再这个 start  能否成功的函数:

    函数的技巧就是从start位置截取每一个单词的长度,比对是否出现过,出现的次数不能超过1次。


    代码:

    class Solution {
    public:
        vector<int> findSubstring(string s, vector<string>& words) {
            vector<int> res;
            if(words.empty())   return res;
            int wordSize=words[0].size();
            int totalWords=words.size();
            int totalLen=wordSize*totalWords;
            
            if(s.size()<totalLen)   return res;
            
            unordered_map<string,int>wordCount;
            for(int i=0;i<totalWords;i++){
                wordCount[words[i]]++;
            }
            
            for(int i=0;i<=s.size()-totalLen;i++){
                if(checkSubstring( s,i, wordCount, wordSize, totalWords))   res.push_back(i);
            }
            return res;
        }
        
        bool checkSubstring(string &s,int start,unordered_map<string,int>&wordCount,int wordSize,int totalWords){
            if(s.size()-start+1<wordSize*totalWords)    return false;
            unordered_map<string,int>wordFound;
            
            for(int i=0;i<totalWords;i++){
                string tmp=s.substr(start+i*wordSize,wordSize);
                if(wordCount[tmp]==0)   return false;
                wordFound[tmp]++;
                if(wordFound[tmp]>wordCount[tmp])   return false;
            }
            
            return true;
        }
    };


  • 相关阅读:
    [UVA10859 放置街灯 Placing Lampposts]
    洛谷7月月赛题解(2020)
    [学习笔记]马拉车-Manacher
    [SP1026] FAVDICE
    [NOIP2013]货车运输
    [洛谷P1801]黑匣子
    [HAOI2015]树上染色
    python-第二块:time模块和datatime模块
    python-作业:员工信息表
    python-第二块,笔记整理和学习内容复习(day7)
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519831.html
Copyright © 2011-2022 走看看