题解 | 字符串排序

字符串排序

https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584

import sys

for line in sys.stdin:
    a = line.split("\n")
    origin_str = a[0] # 字符串不可更改,无法交换元素
    lower_c_list = [(i,c) for i,c in enumerate(origin_str.lower())] #将字符串小写,将字符和原始位置信息保存到元组中
    # print(lower_c_list)
    sorted_l_c = sorted([(i,c) for i,c in lower_c_list if c.isalpha()],key=lambda x:x[1]) # 只对字母进行排序
    # print(sorted_l_c)
    
    # 按照排序后的元组中的初始位置保存原字符串中的字符,排序必须是稳定的,即相同元素排序后相对位置不变
    new_str = ""
    i = 0 # 字母的相对位置
    for c in origin_str:
        if  not c.isalpha(): # 首先对非字母字符进行保存,终止该次循环,进入下次循环
            new_str += c
            continue
        else:
            new_str += origin_str[sorted_l_c[i][0]]
            i += 1
    print(new_str)
        


        

全部评论

相关推荐

10-19 14:15
兰州大学 Java
黄花菜豆:咱俩bg很一致啊uu而且我也做过这个仿小红书,感觉有点太深了短期内不好驾驭啊怕被问穿
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务