删除字符串中出现次数最少的字符

题目描述

实现删除字符串中出现次数最少的字符,若多个字符出现次数一样,则都删除。输出删除这些单词后的字符串,字符串中其它字符保持原来的顺序。


输入描述:

字符串只包含小写英文字母, 不考虑非法输入,输入的字符串长度小于等于20个字节。



输出描述:

删除字符串中出现次数最少的字符后的字符串。


输入例子:
abcdd
  
  
输出例子:

dd

题目分析:
注意题目中几个要注意的问题:
(1)输入的字符串长度<=20
(2) 删除字符串中出现次数最少的字符串,而保留的字符顺序不发生改变
因为要统计到每个字符出现的次数 所以可以使用字典 这里我使用到了OrderDict 其实使用Counter这种字典类会更方便
python代码实现:
import sys
from collections import OrderedDict
def deleteChar(line):
    orderDict=OrderedDict()
    #遍历字符串中的每个单词
    for c in line:
        if c not in orderDict:
            orderDict[c]=1
        else:
            orderDict[c]+=1
    #对字典按照出现的次数进行排序
    #reverse=False是从小到大进行排序
    sorted(orderDict.iteritems(),key=lambda x:x[1],reverse=False)
    #print result
    #从出现次数最小的开始删除
    #获得字符出现的最小的次数
    minTime=min(orderDict.values())
    #print minTime
    #print orderDict.values()
    for item in orderDict:
        if orderDict[item]<=minTime:
            orderDict.pop(item)
    #print orderDict
    s=''
    for c in line:
        if c in orderDict:
            s+=c
    return s

try:
    while True:
        line=sys.stdin.readline()
        if not line:
            break
        if len(line[:-1])>20:
            break
        s=deleteChar(line[:-1])
        print s
        # s=''
        # for item in leftList:
        #     s+=item
        # print s

except:
    pass





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值