题目地址:
https://leetcode.com/problems/substring-with-concatenation-of-all-words/
给定一个字符串 s s s和一个长 n n n的字符串数组 A A A, A A A里每个单词的长度都相等,都是 w w w,要求寻找所有的位置 i i i使得 s [ i : i + n w − 1 ] s[i:i+nw-1] s[i:i+nw−1]恰好是 A A A中所有字符串按某个顺序的拼接。
先将 A A A的所有字符串加入一个哈希表,接着开始遍历 s s s。我们将对于 s s s的遍历分为 w w w次,每次从 [ 0 , w ) [0,w) [0,w)其中一个下标出发,设 0 ≤ t < w 0\le t<w 0≤t<w,那么可以得出 n n n个字符串 s [ t , t + w ) , s [ t + w , t + 2 w ) , . . . , s [ t + ( n − 1 ) w , t + n w ) s[t,t+w), s[t+w,t+2w),...,s[t+(n-1)w,t+nw) s[t,t+w),s[t+w,t+2w),...,s[t+(n−1)w,t+nw),只需要看一下这 n n n个字符串是不是恰好是 A A A中的那些字符串即可。但是这里,直接比较两个哈希表是否相等效率太低,我们可以另外开一个变量,这个变量存这 n n n个字符串里包含于多重集 A A A的那些字符串有多少个( A A A中可能有重复,所以要视 A A A为一个多重集),如果恰好是 n n n个,就说明两个哈希表相等了。代码如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<>();
if (words.length == 0) {
return res;
}
// 存一下words里所有的字符串
Map<String, Integer> tot = new HashMap<>();
for (String word : words) {
tot.put(word, tot.getOrDefault(word, 0) + 1);
}
int w = words[0].length(), n = words.length;
// 枚举每次遍历的起点
for (int i = 0; i < w; i++) {
// 存长n的滑动窗口(这里长n的意思是恰好包含n个长w的单词)里所有字符串及其出现次数
Map<String, Integer> cnt = new HashMap<>();
// 存cnt统计的包含于多重集words的字符串个数
int count = 0;
// 枚举接下来要统计的字符串的起始位置
for (int j = i; j + w <= s.length(); j += w) {
// 如果窗口长度大于n了,就要删掉前面那个出了窗口的字符串
if (j >= i + w * n) {
String sub = s.substring(j - n * w, j - (n - 1) * w);
// 如果cnt里sub的计数小于等于tot,意味着cnt里的sub子集是包含与tot的sub子集的,此时要减少计数
if (tot.containsKey(sub) && cnt.get(sub) <= tot.get(sub)) {
count--;
}
cnt.put(sub, cnt.get(sub) - 1);
}
String sub = s.substring(j, j + w);
cnt.put(sub, cnt.getOrDefault(sub, 0) + 1);
if (tot.containsKey(sub) && cnt.get(sub) <= tot.get(sub)) {
count++;
}
if (count == n) {
res.add(j - (n - 1) * w);
}
}
}
return res;
}
}
时间复杂度 O ( l s w + n w ) O(l_sw+nw) O(lsw+nw),空间 O ( n w ) O(nw) O(nw)。