字母排序 | HJ26 字符串排序
# 最优解 while True: try: string=input() temp=list(string) alphastring=[]#所有字母的列表 for i in string: if i.isalpha(): alphastring.append(i) alphastring.sort(key=str.upper)#将所有字母不论大小写排序,相同时保证之前输入的顺序不变 j=0 for i in range(len(temp)): if temp[i].isalpha():#对字母进行排序 temp[i]=alphastring[j] j+=1 print(''.join(temp)) except: break # 我的代码 while True: try: s = list(input()) tmp_s = ''.join([ch for ch in s if ch.isalpha()]) sort_s = '' for i in range(len(tmp_s)): min_tmp = tmp_s[i] min_indx = i for j in range(i + 1, len(tmp_s)): if tmp_s[j].isalpha() and tmp_s[j].lower() < min_tmp.lower() and \ tmp_s[j].lower() != min_tmp.lower(): min_tmp = tmp_s[j] min_indx = j sort_s += min_tmp tmp_s = sort_s + tmp_s[i:min_indx] + tmp_s[min_indx + 1:] i, j = 0, 0 start = 0 res = [] while i < len(s): j = i while j < len(s) and s[j].isalpha(): j += 1 res.append(sort_s[start:start+j-i]) start = start+j-i if j < len(s): res.append(s[j]) i = j + 1 print(''.join(res)) except: break
用时:2.5h
思路:1、提取所有字母单独排序;2、字母相同但大小写不同时,若需要按输入顺序排序,sort(key=lambda x:x.lower())全转小写且按原输入顺序排序;3、遍历原字符串,按照非字母位置构造新字符串
华为笔试刷题 文章被收录于专栏
高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107