[英]function to return the first possible substring containing all the elements of substring
如何修改myStr
function 以返回包含str2
的所有元素的第一個可能的 substring (從左側遍歷)。 例如:給定str1 = 'xBxxAxxCxxAxCxxBxxxAxCxBxxxAxxBxCx'
和str2 = "ABC"
, function 應該return "BxxAxxC"
。
str1 = input("Enter the first string: ")
str2 = input("Enter the second string to check if the characters exist in the first string: ")
def myStr(str1, str2):
if all(i in str1 for i in str2):
return True
else:
return False
myStr(str1, str2)
如果 str2 不包含任何重復字母,您可以將其字符 map 到它們在 str1 中的第一個位置,並獲得最小和最大位置之間的范圍:
例如:
str1 = 'xBxxAxxCxxAxCxxBxxxAxCxBxxxAxxBxCx'
str2 = "ABC"
pos = [str1.find(c) for c in str2]
result = str1[min(pos):max(pos)+1]
print(result) # BxxAxxC
如果 str1 中沒有出現 str2 的所有字符,這將產生一個空字符串
如果 str2 可以包含重復的字母,那么位置列表 (pos) 需要包含多個重復字符的位置:
pos = [i for r in [list(str2)] for i,c in enumerate(str1)
if c in r and not r.remove(c)]
假設不應該在str2
中的最左邊的字符被排除,您可以執行以下操作:
str2
中的字符創建一個集合str1
中的字符並將它們從該集中刪除。def myStr(str1, str2):
todo = set(str2)
start = -1
for i, ch in enumerate(str1):
if not todo:
return str1[start:i]
if ch in todo:
todo.discard(ch)
if start < 0:
start = i
您可以使用set
操作,為每個前綴檢查所有字母是否都在其中
set(str2) - set(str1[:1])
set(str2) - set('xB') # {'C', 'A'}
set(str2) - set('xBxxA') # {'C'}
set(str2) - set('xBxxAxxC') # set()
def myStr(str1, str2):
chars_to_have = set(str2)
i = 0
while chars_to_have - set(str1[:i]) != set() and i < len(str1):
i += 1
return str1[:i]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.