Python查找字符串s1中含有s2子串的个数

该博客探讨了一种字符串匹配的算法,通过遍历输入字符串s1并切片与目标字符串s2进行比较,计算匹配次数。文章详细展示了算法过程,并以'dabcddabc'和'abc'为例进行了演示,输出了匹配的次数为2。
思路:从s1的第0位开始切片len(s2)个字符串进行比较,相同则计数加1,依次后移,直到最后.
def search_substr(s1, s2):
    if len(s2) > len(s1):
        return 0
    cnt = 0
    for i in range(len(s1)):
        print(i)
        tmp = s1[i:i+len(s2)]
        print(tmp)
        if s2 in tmp:
            cnt += 1
    return cnt

print(search_substr("dabcddabc","abc"))

输出:

0
dab
1
abc
2
bcd
3
cdd
4
dda
5
dab
6
abc
7
bc
8
c

2
以下是使用 Python 实现的代码,用于找出最左侧的 `s2` 以长度 `k` 冗余覆盖 `s1` 的子串的首个元素的下标,若没有则返回 -1: ```python def get_char_count(input_str): char_count_dict = {} for i in input_str: if i in char_count_dict: char_count_dict[i] += 1 else: char_count_dict[i] = 1 return char_count_dict # 处理输入 s1 = input() s2 = input() k = int(input()) def cal(s1, s2, k): # 数组的下标就是字母的 ASCII 码 s1_char_count = [0 for x in range(128)] for i in range(len(s1)): s1_char_count[ord(s1[i])] += 1 # s1 字符总数 total = len(s1) # s2 中出现 s1 字符的个数,先统计固定长度 for j in range(len(s1) + k): if (s1_char_count[ord(s2[j])] > 0): total -= 1 s1_char_count[ord(s2[j])] -= 1 if (total == 0): return 0 # 滑动窗口求解 for i in range(1, len(s2) - len(s1) - k + 1): if (s1_char_count[ord(s2[i - 1])] >= 0): total += 1 s1_char_count[ord(s2[i - 1])] += 1 if (s1_char_count[ord(s2[i - 1 + len(s1) + k])] > 0): total -= 1 s1_char_count[ord(s2[i - 1 + len(s1) + k])] -= 1 if (total == 0): return i return -1 # 长度限制,不可能存在覆盖子串 if (len(s2) < len(s1) + k): print(-1) else: print(cal(s1, s2, k)) ``` ### 代码解释 1. **字符计数函数 `get_char_count`**:用于统计字符串中每个字符的出现次数,并以字典形式返回。 2. **输入处理**:通过 `input()` 函数获取 `s1`、`s2` 和 `k` 的值。 3. **`cal` 函数**: - 初始化 `s1_char_count` 数组,用于记录 `s1` 中每个字符的出现次数。 - 统计 `s1` 的字符总数 `total`。 - 先统计 `s2` 中前 `len(s1) + k` 个字符中 `s1` 字符的出现情况,若满足条件则返回 0。 - 使用滑动窗口,依次移动窗口,更新 `total` 和 `s1_char_count` 的值,若满足条件则返回当前窗口的起始下标。 4. **长度检查**:若 `s2` 的长度小于 `len(s1) + k`,则直接返回 -1。 ### 复杂度分析 - **时间复杂度**:$O(n2)$,其中 $n2$ 是 `s2` 的长度。 - **空间复杂度**:$O(1)$,因为只使用了固定大小的数组。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值