Leetcode:substring with concatenation of all Words

Source: Internet
Author: User

Substring with concatenation of all Words
You is given a string, s, and a list of words, words, that is all of the same length. Find all starting indices of substring (s) in S that's 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 to the indices: [0,9] (order does not matter).

Test Instructions
Given a string of s and a string array, the length of the string in l,l is equal, find all the substrings in S, the substring contains all the characters in L once and does not contain any other characters, returning all the starting positions of this string.

Analysis
The string array L is built with a map character window that matches the character window from the first character of the string s and slides backwards until the last character of S, outputting the matching result.

C++11 Code

//Time complexity O (n*m), Space complexity O (m)classSolution { Public: vector<int>Findsubstring (stringS vector<string>& dict) {size_t wordlength = Dict.front (). Length (); size_t catlength = wordlength * Dict.size (); vector<int>Resultif(S.length () < catlength)returnResult unordered_map<string, int>WordCount; for(Auto Const& Word:dict) {++wordcount[word]; } for(Autoi = begin (s); I <= prev (end (s), catlength); ++i) { unordered_map<string, int>Unused (WordCount); for(Autoj = i; J! = Next (i, catlength); J + = Wordlength) {Autopos = Unused.find (string(J, Next (J, Wordlength)));if(pos = = Unused.end () | | pos->second = =0) Break;if(--pos->second = =0) Unused.erase (POS); }if(unused.size () = =0) Result.push_back (distance (begin (s), i)); }returnResult }};

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode:substring with concatenation of all Words

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.