2025-04-26:统计重新排列后包含另一个字符串的子字符串数目Ⅰ。用go语言,给定两个字符串 word1 和 word2。如果存在一个字符串 x,使得经过重新排列后,word2 是 x 的一个前缀,那么 x 就被称为“合法”的字符串。
请你计算并返回 word1 中所有满足“合法”条件的子字符串的数量。
1 <= word1.length <= 100000。
1 <= word2.length <= 10000。
word1 和 word2 都只包含小写英文字母。
输入:word1 = "bcca", word2 = "abc"。
输出:1。
解释:
唯一合法的子字符串是 "bcca" ,可以重新排列得到 "abcc" ,"abc" 是它的前缀。
题目来自leetcode3297。
因此,总体额外空间复杂度: O(1)。
该算法通过差异数组和双指针滑动窗口,线性高效地统计满足条件的合法子串数,额外空间开销固定,适合处理长度较大的字符串。
package main
import (
"fmt"
)
func validSubstringCount(word1 string, word2 string)int64 {
diff := make([]int, 26)
for _, c := range word2 {
diff[c-'a']--
}
cnt := 0
for _, c := range diff {
if c < 0 {
cnt++
}
}
var res int64
l, r := 0, 0
for l < len(word1) {
for r < len(word1) && cnt > 0 {
update(diff, int(word1[r]-'a'), 1, &cnt)
r++
}
if cnt == 0 {
res += int64(len(word1) - r + 1)
}
update(diff, int(word1[l]-'a'), -1, &cnt)
l++
}
return res
}
func update(diff []int, c, add int, cnt *int) {
diff[c] += add
if add == 1 && diff[c] == 0 {
// 表明 diff[c] 由 -1 变为 0
*cnt--
} elseif add == -1 && diff[c] == -1 {
// 表明 diff[c] 由 0 变为 -1
*cnt++
}
}
func main() {
word1 := "bcca"
word2 := "abc"
result := validSubstringCount(word1, word2)
fmt.Println(result)
}
Python完整代码如下:
package main
import (
"fmt"
)
func validSubstringCount(word1 string, word2 string)int64 {
diff := make([]int, 26)
for _, c := range word2 {
diff[c-'a']--
}
cnt := 0
for _, c := range diff {
if c < 0 {
cnt++
}
}
var res int64
l, r := 0, 0
for l < len(word1) {
for r < len(word1) && cnt > 0 {
update(diff, int(word1[r]-'a'), 1, &cnt)
r++
}
if cnt == 0 {
res += int64(len(word1) - r + 1)
}
update(diff, int(word1[l]-'a'), -1, &cnt)
l++
}
return res
}
func update(diff []int, c, add int, cnt *int) {
diff[c] += add
if add == 1 && diff[c] == 0 {
// 表明 diff[c] 由 -1 变为 0
*cnt--
} elseif add == -1 && diff[c] == -1 {
// 表明 diff[c] 由 0 变为 -1
*cnt++
}
}
func main() {
word1 := "bcca"
word2 := "abc"
result := validSubstringCount(word1, word2)
fmt.Println(result)
}
·
我们相信 Go 语言和算法为普通开发者提供了强有力的“面试利器”,并致力于分享全面的编程知识。在这里,您可以找到最新的 Go 语言教程、算法解析、提升面试竞争力的秘籍以及行业动态。
欢迎关注“福大大架构师每日一题”,让 Go 语言和算法助力您的职业发展
·
更新时间:2025-04-29
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-=date("Y",time());?> All Rights Reserved. Powered By bs178.com 闽ICP备11008920号
闽公网安备35020302034844号