📜  Python – 字符串中可能的子字符串计数

📅  最后修改于: 2022-05-13 01:54:40.932000             🧑  作者: Mango

Python – 字符串中可能的子字符串计数

给定目标字符串和参数子字符串,计算可以使用字符串字符构造多少个子字符串,不允许重复。

方法 #1:使用 count() + min() + set()

上述功能的组合可以用来解决这个问题。在此,我们将 arg字符串的每个元素的计数除以目标字符串字符的计数,并使用 min() 返回最低元素。背后的逻辑是,任何高于 min 的元素都意味着从该字符串开始会丢失最小元素。

Python3
# Python3 code to demonstrate working of
# Possible Substring count from String
# Using min() + list comprehension + count()
 
# initializing string
test_str = "gekseforgeeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing arg string
arg_str = "geeks"
 
# using min and count to get minimum possible
# occurrence of character
res = min(test_str.count(char) // arg_str.count(char) for char in set(arg_str))
 
# printing result
print("Possible substrings count : " + str(res))


Python3
# Python3 code to demonstrate working of
# Possible Substring count from String
# Using Counter() + list comprehension
from collections import Counter
 
# initializing string
test_str = "gekseforgeeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing arg string
arg_str = "geeks"
 
# using Counter to get character frequencies
temp1 = Counter(test_str)
temp2 = Counter(arg_str)
res = min(temp1[char] // temp2[char] for char in temp2.keys())
 
# printing result
print("Possible substrings count : " + str(res))


输出
The original string is : gekseforgeeks
Possible substrings count : 2

方法 #2:使用 Counter() + 列表推导

这是可以执行此任务的另一种方式。在此,我们使用 Counter() 执行计数任务,列表推导用于将结果绑定在一起,使用 min() 执行与先前方法类似的任务。

Python3

# Python3 code to demonstrate working of
# Possible Substring count from String
# Using Counter() + list comprehension
from collections import Counter
 
# initializing string
test_str = "gekseforgeeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing arg string
arg_str = "geeks"
 
# using Counter to get character frequencies
temp1 = Counter(test_str)
temp2 = Counter(arg_str)
res = min(temp1[char] // temp2[char] for char in temp2.keys())
 
# printing result
print("Possible substrings count : " + str(res))
输出
The original string is : gekseforgeeks
Possible substrings count : 2