鉴于长度为N的字符串S,代表一个句子,任务是打印最高和最低平均字符的ASCII值的话。
例子:
Input: S = “every moment is fresh beginning”
Output:
Word with minimum average ASCII values is “beginning”.
Word with maximum average ASCII values is “every”.
Explanation:
The average of ASCII values of characters of the word “every” = ((101+118+101+114+121)/5 =111)
The average of ASCII values of characters of the word “moment” =: (( 109+111+109+101+110+116)/6 = 109.33333)
The average of ASCII values of characters of the word “is” = ((105+115)/2 =)
The average of ASCII values of characters of the word “fresh” = ((102+114+101+115+104)/5 = 110)
The average of ASCII values of characters of the word “beginning” = ((98+101+103+105+110+110+105+110+103)/9 =105).
Therefore, the word with minimum of average of ASCII values is “beginning” and maximum of average ASCII values is “every”.
Input: S = “sky is blue”
Output:
Word with minimum average ASCII values is “blue”.
Word with maximum average ASCII values is “sky”.
方法:想法是使用 split()函数。请按照以下步骤解决问题:
- 使用 split()函数拆分由空格分隔的字符串的所有单词。将它存储在一个列表中,比如lis[]。
- 初始化四个变量,比如maxi、mini、maxId和minId , 存储 ASCII 值平均值的最大值、ASCII 平均值的最小值、列表 lis 中平均 ASCII 值最大的单词的索引以及列表lis[] 中ASCII 平均值最小的单词的索引分别。
- 定义一个函数,例如averageValue(),以查找字符串的平均ASCII 值。
- 遍历列表lis[]并执行以下操作:
- 对于列表lis[]中的每个第i个单词, 并将其存储在一个变量中,比如curr。
- 如果curr> maxi,则将maxi更新为maxi = curr并分配maxId = i。
- 如果curr< mini,则将mini更新为mini = curr并分配minId = i。
- 完成上述步骤后,打印单词lis[minId]和lis[maxId]及其字符的 ASCII 值的最小和最大平均值。
下面是上述方法的实现:
Python3
# Python implementation of the above approach
# Function to find the average
# of ASCII value of a word
def averageValue(s):
# Stores the sum of ASCII
# value of all characters
sumChar = 0
# Traverse the string
for i in range(len(s)):
# Increment sumChar by ord(s[i])
sumChar += ord(s[i])
# Return the average
return sumChar // len(s)
# Function to find words with maximum
# and minimum average of ascii values
def printMinMax(string):
# Stores the words of the
# string S separated by spaces
lis = list(string.split(" "))
# Stores the index of word in
# lis[] with maximum average
maxId = 0
# Stores the index of word in
# lis[] with minimum average
minId = 0
# Stores the maximum average
# of ASCII value of characters
maxi = -1
# Stores the minimum average
# of ASCII value of characters
mini = 1e9
# Traverse the list lis
for i in range(len(lis)):
# Stores the average of
# word at index i
curr = averageValue(lis[i])
# If curr is greater than maxi
if(curr > maxi):
# Update maxi and maxId
maxi = curr
maxId = i
# If curr is lesser than mini
if(curr < mini):
# Update mini and minId
mini = curr
minId = i
# Print string at minId in lis
print("Minimum average ascii word = ", lis[minId])
# Print string at maxId in lis
print("Maximum average ascii word = ", lis[maxId])
# Driver Code
S = "every moment is fresh beginning"
printMinMax(S)
Minimum average ascii word = beginning
Maximum average ascii word = every
时间复杂度: O(N)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live