240
生活,简单就好!

Python编程题15--RGB字符串排序

题目

给定一个字符串,里面只包含 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)))

更多Python编程题,等你来挑战:Python编程题汇总(持续更新中……)

posted @ 2020-10-25 07:29  wintest  阅读(583)  评论(0编辑  收藏  举报