题目描述:
给定两个字符串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)