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 words exactly once and without any intervening characters.
Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"] Output:[]
题意:在字符串s中提取字串,当words数组所有项顺序不定的组合成的字符串与字串相等时,将字串的起始索引存入结果返回
代码如下:
/** * @param {string} s * @param {string[]} words * @return {number[]} */ var findSubstring = function(s, words) { let res=[]; if(s.length==0 || words.length==0) return res; let n=words.length,m=words[0].length; let m1={}; // 将所有单词存入哈希表 for(let w of words){ m1[w]?m1[w]++:(m1[w]=1) } for(let i=0;i<=s.length-n*m;i++){ let m2={}; let j=0; for(j=0;j<n;j++){ // 获取长度为m的字串t let t=s.substr(i+j*m,m); // 如果m1中不存在则跳出循环 if(!m1[t]) break; // 如果m1中存在字串t,则存入m2 m2[t]?m2[t]++:(m2[t]=1); // 如果m2中出现的单词次数比m1多,跳出循环 if(m2[t]>m1[t]) break; } if(j==n) res.push(i); } return res; };
30. Substring with Concatenation of All Words(js)
原文:https://www.cnblogs.com/xingguozhiming/p/10393089.html