LeetCode 30 - 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).

public List<Integer> findSubstring(String S, String[] L) {
    List<Integer> result = new ArrayList<Integer>();
    int len = L[0].length();
    if(L.length==0 || len == 0 || len>S.length()) return result;
    
    Map<String, Integer> map = new HashMap<>();
    for(String str: L) {
        map.put(str, map.containsKey(str)?map.get(str)+1:1);
    }
    
    int wordLen = len * L.length;
    Map<String, Integer> map2 = new HashMap<>();
    for(int i=0; i<=S.length()-wordLen; i++) {
        map2.clear();
        String word = S.substring(i, i+wordLen);
        boolean found = true;
        for(int j=0; j<=word.length()-len; j += len) {
            String slice = word.substring(j, j+len);
            if(map.containsKey(slice)) {
                int count = map2.containsKey(slice) ? map2.get(slice)+1 : 1;
                map2.put(slice, count);
                if(count > map.get(slice)) {
                    found = false;
                    break;
                }
            } else {
                found = false;
                break;
            }
        }
        if(found) {
            result.add(i);
        }
    }
    
    return result;
}

 

又重构了一下代码,结构更加清晰。

public List<Integer> findSubstring(String s, String[] words) {
    List<Integer> list = new ArrayList<>();
    int L = s.length(), N = words[0].length();
    int M = N * words.length;
    if(L == 0 || N == 0 || M > L) return list;
    Map<String, Integer> dict = new HashMap<>();
    for(String word:words) {
        Integer cnt = dict.get(word);
        dict.put(word, cnt == null ? 1 : cnt+1);
    }
    for(int i=0; i<=L-M; i++) {
        String str = s.substring(i, i+M);
        if(containWords(str, words, dict)) {
            list.add(i);
        }
    }
    return list;
}

private boolean containWords(String str, String[] words, Map<String, Integer> dict) {
    int N = words[0].length();
    Map<String, Integer> map = new HashMap<>();
    for(int i=0; i<str.length(); i+=N) {
        String word = str.substring(i, i+N);
        Integer cnt = map.get(word);
        cnt = cnt == null ? 1 : cnt+1;
        map.put(word, cnt);
        if(!dict.containsKey(word) || cnt > dict.get(word)) return false;
    }
    return true;
}

 

你可能感兴趣的:(LeetCode 30 - Substring with Concatenation of All Words)