首页30. Substring with Concatenation of All Words

    xiaoxiao2021-03-25  60

    题目: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.

    解析:先把L放到一个map里面去,key为单词,value为该单词在L中出现的次数。再遍历S,以S中每个字母为开头时,寻找是否存在满足题目要求的子串:发现单词匹配,就从dictCopy里面给这个单词出现的次数减一,如果一切匹配,就不会出现num==null或者num==0的情况。

    解答代码: public class Solution {      public List<Integer> findSubstring(String S, String[] L) {          Map<String, Integer> dict = new HashMap<>();          for (String l : L) {              if (!dict.containsKey(l)) {                  dict.put(l, 0 );              }                            dict.put(l, dict.get(l)+ 1 );          }                    int len = L[ 0 ].length();          int lenSum = len*L.length;                    List<Integer> list = new ArrayList<>();                    traverseS : for ( int i= 0 ; i<=S.length()-lenSum; i++) {              Map<String, Integer> dictCopy = new HashMap<>(dict);                            for ( int j=i; j<i+lenSum; j=j+len) {                  String s = S.substring(j, j+len);                  Integer num = dictCopy.get(s);                  if (num== null || num== 0 )                      continue traverseS;                  num--;                  dictCopy.put(s, num);              }                            list.add(i);          }                    return list;      } }

    转载请注明原文地址: https://ju.6miu.com/read-37949.html

    最新回复(0)