首页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.

解析:先把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;
     }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值