【LeetCode】 30. Substring with Concatenation of All Words 串联所有单词的子串(Hard)(JAVA)
题目地址: https://leetcode.com/problems/substring-with-concatenation-of-all-words/
题目描述:
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
Output: []
题目大意
给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
解题方法
用一个 Map 把所有的单词存起来,移动位置判断该单词是否在 Map 中。
note:
1、words 可能是重复的,存入 Map 的时候要计算次数。
2、words 里面的单词长度都是相同的,只要每次移动 word.length() 然后判断是否在 words 里即可。
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<>();
if (words.length == 0 || words[0].length() == 0 || s.length() < words[0].length() * words.length) return res;
int len = words[0].length();
int allLen = len * words.length;
Map<String, Integer> origin = new HashMap<>();
Map<String, Integer> cur;
for (int i = 0; i < words.length; i++) {
Integer temp = origin.get(words[i]);
if (temp == null) {
origin.put(words[i], 1);
} else {
origin.put(words[i], temp + 1);
}
}
for (int i = 0; i <= s.length() - allLen; i++) {
if (origin.get(s.substring(i, i + len)) == null) continue;
cur = new HashMap<>(origin);
int j = 0;
for (; j < words.length; j++) {
String temp = s.substring(i + len * j, i + len * (j + 1));
Integer count = cur.get(temp);
if (count == null || count <= 0) break;
cur.put(temp, count - 1);
}
if (j >= words.length) res.add(i);
}
return res;
}
}
执行用时 : 146 ms, 在所有 Java 提交中击败了 39.26% 的用户
内存消耗 : 41.8 MB, 在所有 Java 提交中击败了 16.49% 的用户