author: Blankj blog : http://blankj.com time : 2018/02/01 desc :
| 17 | * </pre> |
| 18 | */ |
| 19 | public class Solution { |
| 20 | public List<Integer> findSubstring(String s, String[] words) { |
| 21 | if (s == null) return Collections.emptyList(); |
| 22 | int len = s.length(); |
| 23 | if (len == 0) return Collections.emptyList(); |
| 24 | int wordsSize = words.length; |
| 25 | if (wordsSize == 0) return Collections.emptyList(); |
| 26 | int wordLen = words[0].length(), end = len - wordsSize * wordLen; |
| 27 | if (end < 0) return Collections.emptyList(); |
| 28 | Map<String, Integer> countMap = new HashMap<>(); |
| 29 | for (String word : words) { |
| 30 | countMap.put(word, countMap.getOrDefault(word, 0) + 1); |
| 31 | } |
| 32 | List<Integer> res = new ArrayList<>(); |
| 33 | Set<Integer> ignores = new HashSet<>(); |
| 34 | for (int i = 0; i <= end; ++i) { |
| 35 | if (ignores.contains(i)) continue; |
| 36 | Map<String, Integer> findMap = new HashMap<>(); |
| 37 | int st = i, count = 0; |
| 38 | List<Integer> ignore = new ArrayList<>(); |
| 39 | for (int j = 0; ; ++j) { |
| 40 | int cur = i + j * wordLen; |
| 41 | if (cur + wordLen > len) break; |
| 42 | String word = s.substring(cur, cur + wordLen); |
| 43 | if (countMap.containsKey(word)) { |
| 44 | findMap.put(word, findMap.getOrDefault(word, 0) + 1); |
| 45 | ++count; |
| 46 | while (findMap.get(word) > countMap.get(word)) { |
| 47 | ignore.add(st); |
| 48 | String tmp = s.substring(st, st += wordLen); |
| 49 | findMap.put(tmp, findMap.get(tmp) - 1); |
| 50 | --count; |
| 51 | } |
| 52 | if (count == wordsSize) { |
| 53 | ignore.add(st); |
| 54 | res.add(st); |
| 55 | String tmp = s.substring(st, st += wordLen); |
| 56 | findMap.put(tmp, findMap.get(tmp) - 1); |
| 57 | --count; |
| 58 | } |
| 59 | } else { |
| 60 | for (int k = i; k <= cur; k += wordLen) { |
| 61 | ignore.add(k); |
| 62 | } |
| 63 | break; |
| 64 | } |
| 65 | } |
| 66 | ignores.addAll(ignore); |
| 67 | } |
| 68 | return res; |
| 69 | } |
| 70 | |
| 71 | public static void main(String[] args) { |
| 72 | Solution solution = new Solution(); |
| 73 | System.out.println(solution.findSubstring("wordgoodgoodgoodbestword", new String[]{"word", "good", "best", "good"})); |
| 74 | System.out.println(solution.findSubstring("barfoothefoobarman", new String[]{"foo", "bar"})); |
| 75 | System.out.println(solution.findSubstring("barfoofoobarthefoobarman", new String[]{"bar", "foo", "the"})); |
| 76 | } |
nothing calls this directly
no outgoing calls
no test coverage detected