归档

30. 串联所有单词的子串

30. 串联所有单词的子串

题目

描述:

给定一个字符串 s 和一个字符串数组 words 。words 中所有字符串 长度相同 。

s 中的 串联子串 是指一个包含 words 中所有字符串以任意顺序排列连接起来的子串。

  • 例如,如果 words = ["ab","cd","ef"], 那么 "abcdef", "abefcd","cdabef", "cdefab","efabcd", 和 "efcdab" 都是串联子串。"acdbef" 不是串联子串,因为它不是 words 中任何排列的连接。

返回所有串联子串在 s 中的开始索引。你可以以 任意顺序 返回答案。

示例 1:

  • 输入: s = "barfoothefoobarman", words = ["foo","bar"]
  • 输出: [0,9]
  • 解释:

    因为 words.length == 2 同时 words[i].length == 3,连接的子字符串的长度必须为 6。

    子串 "barfoo" 开始位置是 0。它是 words 中以 ["bar","foo"] 顺序排列的连接。

    子串 "foobar" 开始位置是 9。它是 words 中以 ["foo","bar"] 顺序排列的连接。

    输出顺序无关紧要。返回 [9,0] 也是可以的。

示例 2:

  • 输入: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
  • 输出: []

示例 3:

  • 输入: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
  • 输出: [6,9,12]

提示:

  • 1 <= s.length <= 10^4
  • 1 <= words.length <= 5000
  • 1 <= words[i].length <= 30
  • words[i] 和 s 由小写英文字母组成

题解

以等长单词为窗口单位

答案必须是连续子串,但其中单词的顺序可以不同,次数必须与 words 完全一致。例如 words = ["foo", "foo"] 需要两个 foo,只有一个不能算答案。本题的关键条件是 words 里所有单词长度相同。设每个单词长度是 wordLen,单词个数是 wordNum,合法答案的总长度固定为 wordLen * wordNum,因此可以把字符串切成长度为 wordLen 的单词块,窗口每次按一个单词块前进。

先用 targetMap 统计 words 里每个单词应出现多少次。切块的起点不能只取下标 0:答案可能从任意下标开始,而从下标 r 开始切出的块,边界都落在模 wordLen 余 r 的位置上。所以按起点 0, 1, …, wordLen - 1 分成 wordLen 组,每组各自切块,再用滑动窗口和 windowMap 维护窗口内各单词块的出现次数。

窗口向右扩时,每次读入一个长度为 wordLen 的单词块。如果这个块不在 targetMap 里,任何包含它的窗口都不可能是答案,于是清空窗口状态,把 left 移到 right(这个块之后)重新开始。如果这个块在目标表里,就把它加入 windowMap。一旦某个单词在窗口里出现次数超标,就不断从左边弹出单词,直到它的次数恢复正常为止。

加入新词前,窗口中每种词的次数都不超过目标次数,因此加入后只可能是这个新词超标。收缩时只需检查 windowMap.get(word) > targetMap.get(word),不必扫描整张表。这里的窗口“合法”仅表示没有无关词或超量词,不代表已经集齐全部目标词。

收缩结束后,每种词都没有超量;若总词数又恰好等于 wordNum,就说明所有词频都已相等。否则只要某一种还缺少,总数就不可能达到目标词数。这解释了为什么代码只检查 count 就可以记录答案。

记录起点 left 后,题目要找所有起点,所以还要继续滑。此时把最左边的单词移出窗口,count 变为 wordNum - 1,后面读入的新单词可以和剩余部分组成下一个答案。

以 s = "barfoofoobarthefoobarman"、words = ["bar", "foo", "the"] 为例,看起点为 0 的那一组。依次读到 bar、foo、foo:第二个 foo 超量,左端移出 bar 和第一个 foo,left = 6。接着读到 bar、the,窗口 foobarthe 三个词各一个,记录起点 6,再移出 foo。随后读到 foo,窗口 barthefoo 又凑齐,记录 9;再读到 bar,记录 12。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public List<Integer> findSubstring(String s, String[] words) {
    List<Integer> res = new ArrayList<>();

    if (s == null || s.length() == 0 || words == null || words.length == 0) {
        return res;
    }

    int wordLen = words[0].length();
    int wordNum = words.length;
    int totalLen = wordLen * wordNum;

    if (s.length() < totalLen) {
        return res;
    }

    Map<String, Integer> targetMap = new HashMap<>();
    for (String word : words) {
        targetMap.put(word, targetMap.getOrDefault(word, 0) + 1);
    }

    for (int i = 0; i < wordLen; i++) {
        int left = i;
        int right = i;
        int count = 0;
        Map<String, Integer> windowMap = new HashMap<>();

        while (right + wordLen <= s.length()) {
            String word = s.substring(right, right + wordLen);
            right += wordLen;

            if (!targetMap.containsKey(word)) {
                windowMap = new HashMap<>();
                count = 0;
                left = right;
            } else {
                windowMap.put(word, windowMap.getOrDefault(word, 0) + 1);
                count++;

                while (windowMap.get(word) > targetMap.get(word)) {
                    String leftWord = s.substring(left, left + wordLen);
                    windowMap.put(leftWord, windowMap.get(leftWord) - 1);
                    count--;
                    left += wordLen;
                }

                if (count == wordNum) {
                    res.add(left);

                    String leftWord = s.substring(left, left + wordLen);
                    windowMap.put(leftWord, windowMap.get(leftWord) - 1);
                    count--;
                    left += wordLen;
                }
            }
        }
    }

    return res;
}

设字符串长为 n、单词数为 m、单词长为 L。每组按 L 步推进,各组总共处理 O(n) 个词块。遇到无关词块时重新建立空词频表,避免反复清扫先前扩容的表。每次截取和首次哈希都要处理 L 个字符,加上建立词频表,期望时间为 O((n + m)L)。空间主要是目标词频与当前窗口中的键,按字符存储计上界为 O(mL),结果另计。

每个可能起点都能唯一归入某个模 wordLen 的分组,因此多组扫描不会漏掉非零偏移的答案。记录答案后只移出一个词、保留其余部分,所以与它重叠的下一个答案(如示例中的 9 紧跟 6)也能被找到。若总需求长度超过 s 长度,直接返回空列表。

完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {

    public static List<Integer> findSubstring(String s, String[] words) {
        List<Integer> res = new ArrayList<>();

        if (s == null || s.length() == 0 || words == null || words.length == 0) {
            return res;
        }

        int wordLen = words[0].length();
        int wordNum = words.length;
        int totalLen = wordLen * wordNum;

        if (s.length() < totalLen) {
            return res;
        }

        Map<String, Integer> targetMap = new HashMap<>();
        for (String word : words) {
            targetMap.put(word, targetMap.getOrDefault(word, 0) + 1);
        }

        for (int i = 0; i < wordLen; i++) {
            int left = i;
            int right = i;
            int count = 0;
            Map<String, Integer> windowMap = new HashMap<>();

            while (right + wordLen <= s.length()) {
                String word = s.substring(right, right + wordLen);
                right += wordLen;

                if (!targetMap.containsKey(word)) {
                    windowMap = new HashMap<>();
                    count = 0;
                    left = right;
                } else {
                    windowMap.put(word, windowMap.getOrDefault(word, 0) + 1);
                    count++;

                    while (windowMap.get(word) > targetMap.get(word)) {
                        String leftWord = s.substring(left, left + wordLen);
                        windowMap.put(leftWord, windowMap.get(leftWord) - 1);
                        count--;
                        left += wordLen;
                    }

                    if (count == wordNum) {
                        res.add(left);

                        String leftWord = s.substring(left, left + wordLen);
                        windowMap.put(leftWord, windowMap.get(leftWord) - 1);
                        count--;
                        left += wordLen;
                    }
                }
            }
        }

        return res;
    }

    public static void main(String[] args) {
        String s1 = "barfoothefoobarman";
        String[] words1 = {"foo", "bar"};

        System.out.println("示例 1 输入: s = \"" + s1 + "\", words = [\"foo\", \"bar\"]");
        System.out.println("示例 1 输出: " + findSubstring(s1, words1));
        System.out.println("-----------------------------");

        String s2 = "wordgoodgoodgoodbestword";
        String[] words2 = {"word", "good", "best", "word"};

        System.out.println("示例 2 输入: s = \"" + s2 + "\", words = [\"word\", \"good\", \"best\", \"word\"]");
        System.out.println("示例 2 输出: " + findSubstring(s2, words2));
        System.out.println("-----------------------------");

        String s3 = "barfoofoobarthefoobarman";
        String[] words3 = {"bar", "foo", "the"};

        System.out.println("示例 3 输入: s = \"" + s3 + "\", words = [\"bar\", \"foo\", \"the\"]");
        System.out.println("示例 3 输出: " + findSubstring(s3, words3));
    }
}

运行结果(OpenJDK 21.0.12):

1
2
3
4
5
6
7
8
示例 1 输入: s = "barfoothefoobarman", words = ["foo", "bar"]
示例 1 输出: [0, 9]
-----------------------------
示例 2 输入: s = "wordgoodgoodgoodbestword", words = ["word", "good", "best", "word"]
示例 2 输出: []
-----------------------------
示例 3 输入: s = "barfoofoobarthefoobarman", words = ["bar", "foo", "the"]
示例 3 输出: [6, 9, 12]
本文由作者按照 CC BY 4.0 进行授权