Substring with Concatenation of All Words

解法速度有点慢,要1000ms 左右,OJ上有人java的答案只要300ms, 不知道大神是怎么写的。。

思路是先把L存成一个HashMap,然后因为L里面word一样长,就可以去check S的substring,在位置 i 每次平移一个wordlength,检查这个word在不在map里,在的话就新建一个curMap再查i+wordLen 到 i + wordLen*2一直查下去,最后比较curMap 和map是不是一致就可以了。

public List<Integer> findSubstring(String S, String[] L) {
    if(S == null || L == null || S.length() == 0|| L.length == 0) return null;
    List<Integer> ret = new ArrayList<Integer>();
    HashMap<String, Integer> map = new HashMap<String, Integer>();

    for(String w: L) {
        if(map.containsKey(w))
            map.put(w, map.get(w)+1);
        else map.put(w, 1);

    }
    int wordLen = L[0].length();
    int j = 0;
    int i = 0;
    while(i + wordLen*L.length <= S.length()) {
        j = 0;
        String temp = new String(S.substring(i, i+wordLen));
        if(map.containsKey(temp)){
            HashMap<String, Integer> curMap = new HashMap<String, Integer>();
            while(j < L.length) {
                temp = new String(S.substring(i + wordLen*(j), i + wordLen*(j+1)));
                if(curMap.containsKey(temp))
                    curMap.put(temp,curMap.get(temp)+1);
                else curMap.put(temp, 1);
                j++;
            }
            if(curMap.equals(map)) ret.add(i);
        }

        i++;

    }
    return ret;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值