[Leetcode] Substring with Concatenation of All Words

时间:2020-12-17 20:05:51

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,找出S中所有这样的子串起点,该子串包含L中的所有元素。

说明:

1)L中存在重复的元素
2)子串不允许间断,即子串从开始到找全L中的所有元素之前,子串中不允许包含L以外的东西,而且,即使当前处理的子串是L中含有的,但是前面已经找够了,这个多余的也是不合法的,若此时还有L中的其他元素没找到,从这个起点开始也是不成功的。
3)L在S中出现的顺序不同考虑,任意顺序,只要全部存在就可以。
 
 1 public class Solution {
 2     public List<Integer> findSubstring(String S, String[] L) {
 3         List<Integer> result = new ArrayList<Integer>();
 4         if (S.length() == 0 || L.length == 0)
 5             return result;
 6         HashMap<String, Integer> total = new HashMap<String, Integer>();
 7         HashMap<String, Integer> has = new HashMap<String, Integer>();
 8         int wordCount = L.length;
 9         int wordLen = L[0].length();
10         int searchEnd = S.length() - wordCount * wordLen;
11         if (searchEnd < 0)
12             return result;
13         for (String s : L) {
14             if (total.containsKey(s))
15                 total.put(s, total.get(s) + 1);
16             else
17                 total.put(s, 1);
18         }
19         for (int i = 0; i <= searchEnd; ++i) {
20             has.clear();
21             int j = i;
22             int iWord = 0;
23             for (; iWord < wordCount; ++iWord) {
24 
25                 String sub = S.substring(j, j + wordLen);
26                 if (!total.containsKey(sub))
27                     break;
28                 // in L, but redundancy
29                 if ((has.containsKey(sub))
30                         && (((has.get(sub) + 1)) > total.get(sub)))
31                     break;
32                 if (has.containsKey(sub))
33                     has.put(sub, has.get(sub) + 1);
34                 else
35                     has.put(sub, 1);
36                 j += wordLen;
37             }
38             if (iWord == wordCount)
39                 result.add(i);
40         }
41         return result;
42     }
43 }