題目
給定一個字符串,裏面只包含 R、G、B 三個字符,請給這個字符串排序,要求最終結果的順序是所有R在最前面,所有G在中間,所有B在最後。
例如:
給定一個字符串GBRRGBGG,排完序後:RRGGGGBB。
實現思路1
- 利用字符串中
count()
方法,統計出 R、G、B 三個字符的個數 - 根據統計三個字符的個數,按RGB順序的要求拼接出最終結果
代碼實現
def string_sort(s):
count_R = s.count("R")
count_G = s.count("G")
count_B = s.count("B")
return "{}{}{}".format(count_R * "R", count_G * "G", count_B * "B")
s = "GBRRGBGG"
print("原來的字符串:{}, 排序後的字符串:{}".format(s, string_sort(s)))
實現思路2
- 設置三個變量 left、current、right,其中 left 用於記錄左側 "R" 最右邊的下一個元素位置,right 用於記錄右側 "B" 最左邊的上一個元素位置,current 則用於記錄當前操作的元素位置
- 因爲 Python 中字符串不可變,所以這裏轉換爲list列表來處理
- 使用
while
循環,判斷條件爲 current 小於等於 right,如果 current 大於 right ,那麼結束循環 - 如果 current 對應的元素爲 "R",那麼把該元素放到 left 位置,在這裏與 left 對應的元素交換即可,交換之後,left、current 均加1
- 如果 current 對應的元素爲 "G",那麼該元素不需要移動,直接讓 current 加1
- 如果 current 對應的元素爲 "B",那麼把該元素與 right 對應的元素交換,交換之後 right 減去1,而 current 保持不變(因爲與 right 對應元素交換後,這個元素可能是 "R",後續循環可能還需要處理)
- 對結果進行處理,通過
join()
方法將列表轉換爲字符串
代碼實現
def string_sort(s):
left, current, right = 0, 0, len(s)-1
str_list = [i for i in s]
while current <= right:
if str_list[current] == "R":
str_list[left], str_list[current] = str_list[current], str_list[left]
left += 1
current += 1
elif str_list[current] == "G":
current += 1
elif str_list[current] == "B":
str_list[current], str_list[right] = str_list[right], str_list[current]
right -= 1
return "".join(str_list)
s = "GBRRGBGG"
print("原來的字符串:{}, 排序後的字符串:{}".format(s, string_sort(s)))