Python程式:從兩個字串建立詞典最小字串
假設我們有兩個字串。我們想要從這些字串中建立一個詞典最小字串。為了建立這個字串,我們比較兩個字串的第一個字母,並從其中一個字串中提取詞典上較小的字母。如果出現平局,即字母相同,我們從第一個字串中提取字母。我們重複這個過程,直到兩個字串都為空。必須返回構建的最小字串。
因此,如果輸入類似於 input_1 = 'TUTORIALS',input_2 = 'POINT',則輸出將為 POINTTUTORIALS
如果我們比較這兩個字串,我們會得到以下逐步過程:
TUTORIALS POINT TUTORIALS OINT = P TUTORIALS INT = PO TUTORIALS NT = POI TUTORIALS T = POIN TUTORIALS = POINT
由於其中一個字串為空,因此整個第一個字串現在被放置在結果最小字串中。所以最終字串是 POINTTUTORIALS。
為了解決這個問題,我們將遵循以下步驟:
- input_1 := input_1 + "z"
- input_2 := input_2 + "z"
- temp_1 := 0
- temp_2 := 0
- res_str := 空字串
- 當 temp_1 < input_1 的大小 且 temp_2 < input_2 的大小 時,執行以下操作:
- 如果 input_1[從索引 temp_1 到字串末尾] < input_2[從索引 temp_2 到字串末尾],則:
- res_str := res_str + input_1[temp_1]
- temp_1 := temp_1 + 1
- 否則:
- res_str := res_str + input_2[temp_2]
- temp_2 := temp_2 + 1
- 如果 input_1[從索引 temp_1 到字串末尾] < input_2[從索引 temp_2 到字串末尾],則:
- res_str := res_str[從索引 0 到字串的倒數第二個元素]
- 如果 temp_1 < (input_1) 的長度,則:
- res_str := res_str + input_1[從索引 temp_1 到字串的倒數第二個元素]
- 如果 temp_2 < (input_2) 的長度,則:
- res_str := res_str + input_2[從索引 temp_2 到字串的倒數第二個元素]
- 返回 res_str
示例
讓我們看看下面的實現以更好地理解:
def solve(input_1, input_2):
input_1 += "z"
input_2 += "z"
temp_1 = 0
temp_2 = 0
res_str = ""
while temp_1 < len(input_1) and temp_2 < len(input_2):
if input_1[temp_1:] < input_2[temp_2:]:
res_str += input_1[temp_1]
temp_1 += 1
else:
res_str += input_2[temp_2]
temp_2 += 1
res_str = res_str[:-1]
if temp_1 < len(input_1):
res_str += input_1[temp_1:-1]
if temp_2 < len(input_2):
res_str += input_2[temp_2:-1]
return res_str
print(solve('TUTORIALS', 'POINT'))輸入
'TUTORIALS', 'POINT'
輸出
POINTTUTORIALS
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP