我有一串小寫英文字母和一個整數子串長度。我必須找到包含最多元音的那個長度的子串。
例子:
s = 'azerdii'
k = 5
可能的 5 個字符子串是:
- 'azerd' 元音數 = 2
- 'zerdi' 元音數 = 2
- 'erdii' 元音數 = 3
所以答案應該是'erdii'
這是我的代碼:
def findSubstring(s, k):
i = 0
lst = []
count = 0
tempL = []
while(i != len(s)):
a = i k
temp = s[i:a]
lst.append(temp)
if a != len(s):
i =1
else:
break
for word in lst:
for alphabet in word:
if alphabet in 'aeiou':
count = 1
tempL.append(count)
print(lst)
print(tempL)
return
s = input()
k = int(input().strip())
print(findSubstring(s, k))
I'm getting
['azerd', 'zerdi', 'erdii']
[2, 4, 7]
但計數應該是
[2, 2, 3]
請原諒我可能有的任何愚蠢的錯誤。我當然會感謝任何幫助。
uj5u.com熱心網友回復:
請嘗試以下操作:
def find_substr(s, k):
substrings = [s[i:i k] for i in range(len(s) - k 1)] # list of substrings
# vowels = [sum(c in 'aeiou' for c in s) for s in substrings]
# print(vowels) # [2, 2, 3]
return max(substrings, key=lambda s: sum(c in 'aeiou' for c in s))
print(find_substr('azerdii', 5)) # 'erdii'
如果您取消注釋被注釋掉的行,您將看到元音的數量正確計算為[2, 2, 3]。
這里,sum(c in 'aeiou' for c in s)獲取字串中元音的個數,s相當于
count = 0
for alphabet in word:
if alphabet in 'aeiou':
count = 1
這反過來與您的代碼相同,除了行count = 0。處理完每個后word,您需要重新設定count。因此,請嘗試添加count = 0您的代碼。
uj5u.com熱心網友回復:
您需要重置第count=017 行。
試試這個代碼
def findSubstring(s, k):
i = 0
lst = []
count = 0
tempL = []
while(i != len(s)):
a = i k
temp = s[i:a]
lst.append(temp)
if a != len(s):
i =1
else:
break
for word in lst:
count = 0
for alphabet in word:
if alphabet in 'aeiou':
count = 1
tempL.append(count)
print(lst)
print(tempL)
return
s = 'azerdii'
k = 5
print(findSubstring(s, k))
uj5u.com熱心網友回復:
您可以使用滑動視窗方法,以獲得最佳時間復雜度單遍解決方案:
def find_substring_length_k_most_vowels(s: str, k: int) -> str:
'''Returns any substring of length k that has the max number of vowels.'''
vowels = set('aeiou')
max_vowel_count = curr_vowel_count = 0
max_window_start, max_window_end = 0, -1
window_start = 0
for window_end, ch in enumerate(s):
if ch in vowels:
curr_vowel_count = 1
if window_end - window_start 1 == k:
if curr_vowel_count > max_vowel_count:
max_vowel_count = curr_vowel_count
max_window_start, max_window_end = window_start, window_end
curr_vowel_count -= 1 if s[window_start] in vowels else 0
window_start = 1
return s[max_window_start:max_window_end 1]
def main() -> None:
s = 'azerdii'
k = 5
print(find_substring_length_k_most_vowels(s, k))
if __name__ == '__main__':
main()
輸出:
erdii
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/348921.html
