zoukankan      html  css  js  c++  java
  • 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;
    };
  • 相关阅读:
    HDU 5115 Dire Wolf (区间DP)
    HDU 4283 You Are the One(区间DP(最优出栈顺序))
    ZOJ 3469 Food Delivery(区间DP好题)
    LightOJ 1422 Halloween Costumes(区间DP)
    POJ 1651 Multiplication Puzzle(区间DP)
    NYOJ 石子合并(一)(区间DP)
    POJ 2955 Brackets(括号匹配一)
    POJ 1141 Brackets Sequence(括号匹配二)
    ZOJ 3537 Cake(凸包+区间DP)
    Graham求凸包模板
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10393089.html
Copyright © 2011-2022 走看看