October 06, 2019

30. Substring with Concatenation of All Words

30. Substring with Concatenation of All Words

Time = O(n), space = O(n).

class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> res = new ArrayList<>();
        if (words == null || words.length == 0 || s == null || s.length() == 0) {
            return res;
        }
        Map<String, Integer> map = new HashMap<>();
        for (String word : words) {
            if (map.containsKey(word)) {
                map.put(word, map.get(word) + 1);
            } else {
                map.put(word, 1);
            }
        }
        
        int wordLen = words[0].length();
        int subLen = words.length * words[0].length();
        for (int i = 0; i < s.length() - subLen + 1; i++) {
            String subStr = s.substring(i, i + subLen);
            if (isSubstring(map, subStr, wordLen)) {
                res.add(i);
            }
        }
        return res;
    }
    
    private boolean isSubstring(Map<String, Integer> map, String subStr, int wordLen) {
        Map<String, Integer> curMap = new HashMap<>();
        for (int i = 0; i < subStr.length() - wordLen + 1; i = i + wordLen) {
            String curWord = subStr.substring(i, i + wordLen);
            if (!map.containsKey(curWord)) {
                return false;
            }
            if (curMap.containsKey(curWord) && curMap.get(curWord) == map.get(curWord)) {
                return false;
            }
            if (curMap.containsKey(curWord)) {
                curMap.put(curWord, curMap.get(curWord) + 1);
            } else {
                curMap.put(curWord, 1);
            }
        }
        return true;
    }
}
comments powered by Disqus