题解 | 字符串排序
字符串排序
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)
海康威视公司福利 1125人发布