zoukankan      html  css  js  c++  java
  • 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)))
    
  • 相关阅读:
    .NET 3.5新特性(转)
    (转)常用正则表达式
    IEC 61850(转)
    好几年了,我又回来了。
    EPR和SAP的一些名词解释(转载)
    为blogs添加风采,添加奥运金牌榜及赛程
    VS2010崩溃重启解决方法.
    C#制作Windows service服务系列二:演示一个定期执行的windows服务及调试(windows service)(转载)
    C#中操作XML (修改完整版) (转)
    C#制作Windows service服务系列一:制作一个可安装、可启动、可停止、可卸载的Windows service
  • 原文地址:https://www.cnblogs.com/wintest/p/13871879.html
Copyright © 2011-2022 走看看