首页 > 试题广场 >

字符串归一化

[编程题]字符串归一化
  • 热度指数:15635 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
通过键盘输入一串小写字母 (a~z) 组成的字符串。
请编写一个字符串归一化程序,统计字符串中相同字符出现的次数,并按字典序输出字符及其出现次数。
例如字符串"babcc"归一化后为"a1b2c2"

数据范围:输入的字符串长度满足 ,保证输入中仅包含小写的英文字母

输入描述:
每个测试用例每行为一个字符串,以'\n'结尾,例如cccddecca


输出描述:
输出压缩后的字符串ac5d2e
示例1

输入

dabcab

输出

a2b2c1d1
import sys
messages = sys.stdin.readline().strip().split()
in_str = messages[0]
res = {}

for i in set(in_str):
    res[i] = in_str.count(i)

final_str = ''
final_res = sorted(res.items(),key = lambda x:x[0])
for k,v in final_res:
    final_str+=k
    final_str+=str(v)
print(final_str)
发表于 2020-06-09 11:41:42 回复(0)
#思考,如果需要循环的话,先对数据去重
#在去重的数据中对元素循环,在原始数据中进行count计算
#直接输出进行拼接 print()默认换行,加上参数end=''不换行输出
str_ = input() #按行输入
str_sort = sorted(set(str_)) #使用set去重后排序
for ch in str_sort:
    print(ch + str(str_.count(ch)),end ='')
print()

编辑于 2019-09-22 13:47:19 回复(0)
list1=list(raw_input())
set1=set(list1)
list2=list(set1)
list2.sort()
str1=''
for item in list2:
    str1+=item
    str1+=str(list1.count(item))
print(str1)


发表于 2019-09-08 21:34:45 回复(1)
a = input()
result = sorted(set(list(a)))
for i in result:
    print(i, a.count(i), end='', sep='')

发表于 2019-09-05 21:05:22 回复(0)
str_ = input()
sorted_char_list = sorted(set(str_))
for ch in sorted_char_list:
    print(ch + str(str_.count(ch)), end="")
print()

编辑于 2019-08-22 16:31:28 回复(0)
s = list(input())
word = sorted(list(set(s)))
dic = dict()
result = '' for elem in s: if elem in dic.keys():
        dic[elem]+=1  else:
        dic[elem] = 1 for param in word:
    result+=param
    result+=str(dic[param]) print(result)
发表于 2019-08-11 22:39:13 回复(0)
"""
使用Counter计数器
"""
import sys
import collections

if __name__ == "__main__":
    # sys.stdin = open("input.txt", "r")
    s = input().strip()
    obj = collections.Counter(s)
    d = sorted(obj.items(), key=lambda c: c[0])
    ans = ""
    for i in range(len(d)):
        ans += str(d[i][0]) + str(d[i][1])
    print(ans)

发表于 2019-07-06 21:25:13 回复(0)
s = input().strip()
s_set = sorted(set(s))
s_ = ''
for index, item in enumerate(s_set):
    s_ += item
    s_ += str(s.count(item))
print(s_)
发表于 2019-07-04 10:53:38 回复(0)