【华为机试】2023年真题B卷(python)-关联子串

发布时间:2023年12月31日

一、题目

题目描述:

给定两个字符串str1和str2,
str1进行排列组合只要有一个为str2的子串则认为str1是str2的关联子串,
请返回子串在str2的起始位置,若不是关联子串则返回-1。

二、示例

示例1

输入输出示例仅供调试,后台判题数据一般不包含示例
输入:
abc efghicbaiii
输出:
5
示例2

输入输出示例仅供调试,后台判题数据一般不包含示例
输入:
abc efghiccaiii
输出:
-1

三、解题思路

简单的字符串处理

四、参考代码?

# -*- coding: utf-8 -*-
'''
@File    :   2023-B-关联子串.py
@Time    :   2023/12/29 18:08:23
@Author  :   mgc 
@Version :   1.0
@Desc    :   None
'''

# import os
# import re
# import sys
# import copy
# import math
# import queue
# import functools
# from queue import Queue
# from collections import Counter, defaultdict

def find_substring_position(s, t):
    
    now = [0] * 26  # 用于记录字符串s中每个字符出现的次数

    # 统计字符串s中每个字符出现的次数
    for c in s:
        now[ord(c) - 97] += 1

    cnt = [[0] * 26 for _ in range(len(t) + 1)]  # 用于记录字符串t中每个位置之前每个字符出现的次数
    for i in range(1, len(t) + 1):
        for j in range(26):
            cnt[i][j] = cnt[i - 1][j]
        cnt[i][ord(t[i - 1]) - 97] += 1

    ans = -1  # 初始化结果为-1
    for i in range(len(t) - len(s) + 1):
        flag = True
        for j in range(26):
            if cnt[i + len(s)][j] - cnt[i][j] != now[j]:
                flag = False
        if flag:
            ans = i
            break

    print(ans)  # 输出结果

s, t = input().split()
find_substring_position(s, t)
文章来源:https://blog.csdn.net/u014481728/article/details/135296522
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。