• 30. Substring with Concatenation of All Words(js)


    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;
    };
  • 相关阅读:
    天梯赛 社交集群(并查集)
    蓝桥杯 正则问题(dfs)
    天梯赛L3-001. 凑零钱(01背包记录物品)
    天梯赛/PAT 二叉树总结
    GPLT天梯赛 L2-022. 重排链表
    蓝桥杯 2的次幂表示(递归)
    排列与组合的一些定理
    卡特兰数
    洛谷P1349 广义斐波那契数列(矩阵快速幂)
    Manacher's Algorithm 马拉车算法(最长回文串)
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10393089.html
Copyright © 2020-2023  润新知