def f(c: str) -> bool: if c >= "a" and c <= "z": return True if c >= "A" and c <= "Z": return True return False try: while True: s = [i for i in input()] n = len(s) if n == 0: print("") continue # print(s) dic = [[] for _ in range(26)] for c in s: if f(c): t = ord(c.lower()) - ord("a") dic[t].append(c) # print(dic) index, p = 0, 0 # 移动到第一个不为空的地方 while index < 26 and len(dic[index]) == 0: index += 1 # 获取该字符出现的长度 m = len(dic[index]) # 枚举s字符串 for i in range(n): # 非字母不动 if not f(s[i]): continue if p < m: s[i] = dic[index][p] p += 1 if p == m: # 重置指针 p = 0 # 移动到下一个不为空的字符集合 index += 1 while index < 26 and len(dic[index]) == 0: index += 1 if index < 26: m = len(dic[index]) print("".join(s)) except Exception: pass
哈希表存储
使用哈希表存储每个字符的出现顺序,最大也就26个。所以可以直接开26个数组用来存储。
再次遍历字符串,对字母位置的字符进行重新装填。