【LeetCode】Substring with Concatenation of All Words 解题报告

【题目】

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S"barfoothefoobarman"
L["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

【解析】

题意:给定一个字符串S和一个字符串数组L,L中的字符串长度都相等,找出S中所有的子串恰好包含L中所有字符各一次,返回子串的起始位置。

把L转化为一个HashMap<String, Integer>,其value表示L中String的个数,因为L中可能包含相同的字符串。

public class Solution {
    public List<Integer> findSubstring(String S, String[] L) {
        List<Integer> ans = new ArrayList<Integer>();
        if (S.length() < 1 || L.length < 1) return ans;
        int len = L[0].length(); //题目说L中每个单词长度一样
        
        //初始化HashMap,注意L中可能包含多个相同的字符串,所以用value表示个数
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for (int j = 0; j < L.length; j++) {
            if (map.containsKey(L[j])) {
            	map.put(L[j], map.get(L[j]) + 1);
            } else {
            	map.put(L[j], 1);
            }
        }
        
        //i的范围很关键,如果直接到S.length()是会超时的
        for (int i = 0; i <= S.length() - L.length * len; i++) {
            int from = i;
            String str = S.substring(from, from + len);
            int cnt = 0;
            while (map.containsKey(str) && map.get(str) > 0) {
                map.put(str, map.get(str) - 1);
                cnt++;
                from += len;
                if (from + len > S.length()) break; //注意越界
                str = S.substring(from, from + len);
            }
            
            //L中每个单词恰好出现一次,加入到结果集
            if (cnt == L.length) {
                ans.add(i);
            }
            
            //为下一次初始化HashMap
            if (cnt > 0) {
            	map.clear();
                for (int j = 0; j < L.length; j++) {
                    if (map.containsKey(L[j])) {
                    	map.put(L[j], map.get(L[j]) + 1);
                    } else {
                    	map.put(L[j], 1);
                    }
                }
            }
        }
        
        return ans;
    }
}

这道题的Test Case有点变态,代码改了好多次,各种没有注意到的边边角角。



=====================

Update on 2015/10/28

该题时间要求已变,上述代码会超时,等待后续更高效的解法,也欢迎大家补充好的解法。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值