comments | difficulty | edit_url | rating | source | tags | |||
---|---|---|---|---|---|---|---|---|
true |
中等 |
1847 |
第 416 场周赛 Q3 |
|
给你两个字符串 word1
和 word2
。
如果一个字符串 x
重新排列后,word2
是重排字符串的 前缀 ,那么我们称字符串 x
是 合法的 。
请你返回 word1
中 合法 子字符串 的数目。
示例 1:
输入:word1 = "bcca", word2 = "abc"
输出:1
解释:
唯一合法的子字符串是 "bcca"
,可以重新排列得到 "abcc"
,"abc"
是它的前缀。
示例 2:
输入:word1 = "abcabc", word2 = "abc"
输出:10
解释:
除了长度为 1 和 2 的所有子字符串都是合法的。
示例 3:
输入:word1 = "abcabc", word2 = "aaabc"
输出:0
解释:
1 <= word1.length <= 105
1 <= word2.length <= 104
word1
和word2
都只包含小写英文字母。
题目实际上是求在
首先,如果
接下来,我们用一个哈希表或长度为
接着,我们用一个滑动窗口
遍历
遍历完
时间复杂度
class Solution:
def validSubstringCount(self, word1: str, word2: str) -> int:
if len(word1) < len(word2):
return 0
cnt = Counter(word2)
need = len(cnt)
ans = l = 0
win = Counter()
for c in word1:
win[c] += 1
if win[c] == cnt[c]:
need -= 1
while need == 0:
if win[word1[l]] == cnt[word1[l]]:
need += 1
win[word1[l]] -= 1
l += 1
ans += l
return ans
class Solution {
public long validSubstringCount(String word1, String word2) {
if (word1.length() < word2.length()) {
return 0;
}
int[] cnt = new int[26];
int need = 0;
for (int i = 0; i < word2.length(); ++i) {
if (++cnt[word2.charAt(i) - 'a'] == 1) {
++need;
}
}
long ans = 0;
int[] win = new int[26];
for (int l = 0, r = 0; r < word1.length(); ++r) {
int c = word1.charAt(r) - 'a';
if (++win[c] == cnt[c]) {
--need;
}
while (need == 0) {
c = word1.charAt(l) - 'a';
if (win[c] == cnt[c]) {
++need;
}
--win[c];
++l;
}
ans += l;
}
return ans;
}
}
class Solution {
public:
long long validSubstringCount(string word1, string word2) {
if (word1.size() < word2.size()) {
return 0;
}
int cnt[26]{};
int need = 0;
for (char& c : word2) {
if (++cnt[c - 'a'] == 1) {
++need;
}
}
long long ans = 0;
int win[26]{};
int l = 0;
for (char& c : word1) {
int i = c - 'a';
if (++win[i] == cnt[i]) {
--need;
}
while (need == 0) {
i = word1[l] - 'a';
if (win[i] == cnt[i]) {
++need;
}
--win[i];
++l;
}
ans += l;
}
return ans;
}
};
func validSubstringCount(word1 string, word2 string) (ans int64) {
if len(word1) < len(word2) {
return 0
}
cnt := [26]int{}
need := 0
for _, c := range word2 {
cnt[c-'a']++
if cnt[c-'a'] == 1 {
need++
}
}
win := [26]int{}
l := 0
for _, c := range word1 {
i := int(c - 'a')
win[i]++
if win[i] == cnt[i] {
need--
}
for need == 0 {
i = int(word1[l] - 'a')
if win[i] == cnt[i] {
need++
}
win[i]--
l++
}
ans += int64(l)
}
return
}
function validSubstringCount(word1: string, word2: string): number {
if (word1.length < word2.length) {
return 0;
}
const cnt: number[] = Array(26).fill(0);
let need: number = 0;
for (const c of word2) {
if (++cnt[c.charCodeAt(0) - 97] === 1) {
++need;
}
}
const win: number[] = Array(26).fill(0);
let [ans, l] = [0, 0];
for (const c of word1) {
const i = c.charCodeAt(0) - 97;
if (++win[i] === cnt[i]) {
--need;
}
while (need === 0) {
const j = word1[l].charCodeAt(0) - 97;
if (win[j] === cnt[j]) {
++need;
}
--win[j];
++l;
}
ans += l;
}
return ans;
}