Python |以最大频率计算给定字符串中的所有前缀

给定一个字符串,打印并计数第一个字母比第二个字母频率高的所有前缀。 从用户那里获取两个字母表并进行比较。第一个字母表中的前缀比第二个字母表中的前缀频率高,这样的前缀会被打印出来,否则结果将为0。 例如:

null
Input : string1 = "geek",         alphabet1 = "e", alphabet2 = "k"Output :gegeegeek3Input : string1 = "geek",        alphabet1 = "k", alphabet2 = "e"Output :0

方法: 取一个空字符串来存储所有前缀的字符串值。然后检查频率高于第二个字母的字母表。如果没有发现这种情况,那么结果将是 0 前缀。 以下是实施情况:

Python3

# Python program to Count all
# prefixes in given string with
# greatest frequency
# Function to print the prefixes
def prefix(string1, alphabet1, alphabet2):
count = 0
non_empty_string = ""
string2 = list (string1)
# Loop for iterating the length of
# the string and print the prefixes
# and the count of query prefixes.
for i in range ( 0 , len (string2)):
non_empty_string = non_empty_string + (string2[i])
if (non_empty_string.count(alphabet1) >
non_empty_string.count(alphabet2)):
# prints all required prefixes
print (non_empty_string)
# increment count
count + = 1
# returns count of the
# required prefixes
return (count)
# Driver Code
print (prefix( "geeksforgeeks" , "e" , "g" ))


输出:

geegeekgeeksgeeksfgeeksfogeeksforgeeksforgegeeksforgeegeeksforgeekgeeksforgeeks10

时间复杂性: O(N),其中N是字符串的长度

辅助空间: O(N)

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享