[Leetcode] [Java] Substring with concatenation of all Words

Source: Internet
Author: User
Tags truncated


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 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).

Test Instructions:

Given a strings, and a set of string array words, all string lengths in the array are the same. Find the start label of all substrings from the string s. These substrings are a combination of all the strings in the words . And each string appears only once and no other characters are inserted between them, and the order of the strings does not matter.

Algorithm Analysis:method One:

* Because the length of all words in L is the same. This is based on Wordlen. Be able to divide s into wordlen groups, the actual meaning is this.

* In the title Barfoothefoobarman example, the word length in L is 3. can be divided into

* Bar|foo|the|foo|bar|man

* Ba|rfo|oth|efo|oba|rma|n

* B|arf|oot|hef|oob|arm|an

Such For each grouping, it is possible to take advantage of the idea of a minimal sliding form, whether the high-speed inference includes the required string.

* Visually, it is necessary to start a search from every character, in fact, using two pointers to find the strings that satisfy the condition in S, and each +wordlen. And will not be repeated to the system * meter. Save

* A lot of time.

Method Two:

The idea is still to maintain a form. If the current word is in the dictionary, move on to the right end of the form. Otherwise the left side of the form can jump to the next word in the string. If the length of the source string is N. The length of the word in the dictionary is L. Because it is not a character. So we need to infer the entire length of the source string as a substring of L.

Each time the length of the string in the source string is truncated in order and the length of all strings in the dictionary is equal, it is inferred that the new truncated substring matches the string in the dictionary and the match is added to the result. A mismatch continues to intercept the new substring in the source string in sequence. Repeat the process until the end.

AC Code:method One:

<span style= "FONT-SIZE:12PX;" >public class solution{public arraylist<integer> findsubstring (String S, string[] L) {ARRAYLIST&L t;integer> list = new arraylist<integer> (), int len = l.length;if (len = = 0) return list;int Wordlen = l[0].length (); map<string, integer> wordsmap = new hashmap<string, integer> (); for (int i = 0; i < len; i++) {int num = 1;i F (Wordsmap.get (l[i]) = null) num + = Wordsmap.get (L[i]); Wordsmap.put (l[i], num);} int slen = s.length (); int max = Slen-wordlen + 1;for (int i = 0; i < Wordlen; i++) {map<string, integer> Nummap = new hashmap<string, integer> (); int count = 0;int start = i;for (int end = start; end < Max; end + = Wordlen) {St Ring TempStr = s.substring (end, End + Wordlen), if (!wordsmap.containskey (TEMPSTR))//The given string array does not include the current string and jumps directly to the next string { Nummap.clear (); count = 0;start = end + wordlen;continue;} int num = 1;if (Nummap.containskey (TEMPSTR)) num + = Nummap.get (TEMPSTR); Nummap.put (TEMPSTR, num); if (NuM <= Wordsmap.get (TEMPSTR)) count++;//only has to add else {while (Nummap.get (TEMPSTR) > Wordsmap.get) only if it is less than the given array element number ( TEMPSTR) {TempStr = s.substring (start, start + Wordlen);//When the number of elements in the current map trailer is greater than the given array element, the map header element nummap.put is removed (TEMPSTR, Nummap.get (TEMPSTR)-1); if (Nummap.get (TEMPSTR) < Wordsmap.get (TEMPSTR)) count--;//removed the element. The number is missing a start + = wordlen;//The corresponding starting element also moves backward a}}if (count = = len) {list.add (start); tempstr = s.substring (start, start + Word Len);//To remove the first element after satisfying the condition, that is, to move back one position at a time, to see if the following conditions are not nummap.put (TempStr, Nummap.get (TEMPSTR)-1); Count--;start + = Wordlen;}    }}return list; }}</span>

Method Two:

public class Solution {public list<integer> findsubstring (String S, string[] L) {list<integer>        Result=new arraylist<integer> (); if (l.length==0| |        S.length () ==0) return result;        int Wordlen=l[0].length ();        Map storing L hashmap<string,integer> map=new hashmap<string,integer> ();            for (int i=0;i<l.length;i++) {Integer value=map.get (l[i]);            if (value==null) value=1;            else value+=1;        Map.put (L[i],value);            } for (int i=0;i+wordlen<=s.length (); i++) {if (i + Wordlen * l.length > S.length ())            {break; } if (Map.containskey (s.substring (I,i+wordlen))) {Boolean b=checkstring (s.substring (i                , I+wordlen*l.length), new hashmap<string,integer> (map), Wordlen);            if (b==true) result.add (i);  }        }      return result;        }//Check string s is not a combination of strings in map public boolean checkstring (string s,hashmap<string,integer> map,int Wordlen) {        Boolean flag=true;        int i=0;            while (S.length () >0) {String temp=s.substring (0,wordlen);            Integer Value=map.get (temp); if (value==null| |                value==0) {flag=false;            Break                }else{value-=1;                Map.put (Temp,value);            S=s.substring (Wordlen);//The substring starts at the character at the specified index until the end of the string.    }} return flag; }}

[Leetcode] [Java] Substring with concatenation of all Words

Related Article

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.