标签:return res 30 Concatenation Substring length let words m1
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; };
标签:return,res,30,Concatenation,Substring,length,let,words,m1 来源: https://www.cnblogs.com/xingguozhiming/p/10393089.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。