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:

  1. S: "barfoothefoobarman"
  2. L: ["foo", "bar"]

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

分析

代码

  1. // Substring with Concatenation of All Words
  2. // 时间复杂度O(n*m),空间复杂度O(m)
  3. public class Solution {
  4. public List<Integer> findSubstring(String s, String[] words) {
  5. final int wordLength = words[0].length();
  6. final int catLength = wordLength * words.length;
  7. List<Integer> result = new ArrayList<>();
  8. if (s.length() < catLength) return result;
  9. HashMap<String, Integer> wordCount = new HashMap<>();
  10. for (String word : words)
  11. wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
  12. for (int i = 0; i <= s.length() - catLength; ++i) {
  13. HashMap<String, Integer> unused = new HashMap<>(wordCount);
  14. for (int j = i; j < i + catLength; j += wordLength) {
  15. final String key = s.substring(j, j + wordLength);
  16. final int pos = unused.getOrDefault(key, -1);
  17. if (pos == -1 || pos == 0) break;
  18. unused.put(key, pos - 1);
  19. if (pos - 1 == 0) unused.remove(key);
  20. }
  21. if (unused.size() == 0) result.add(i);
  22. }
  23. return result;
  24. }
  25. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/simulation/substring-with-concatenation-of-all-words.html