题解 | #删除字符串中出现次数最少的字符#

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

http://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9

#一开始以为要分三种情况,即abb,aabbddd,ddddd,后来发现不用,都用最后那几行统一处理即可
while True:
    try:
        s=input()
        ss=set(s)
        adict={}
        snew=''
        for i in ss:
            adict[i]=s.count(i)  #统计元素个数可以直接用collections.Counter()方法
        alist=sorted(adict.items(),key=lambda stu:stu[1])
        # print(alist)
        # if alist[0][1]<alist[1][1]:
        #     print(s.replace(alist[0][0],''))
        # elif alist[0]==alist[-1]:
        #     print()
        # else :
        subs = ''
        for item in alist:
            if item[1]==alist[0][1]:
                subs+=item[0]
        for i in subs:
            s=s.replace(i,'')
        print(s)
    except:
        break
#第二种更简洁:
while True:
    try:
        s = input()
        dic, res = {}, ''
        for c in s:
            if c not in dic:
                dic[c] = 1
            else:
                dic[c] += 1  #统计元素个数可以直接用collections.Counter()方法
        Min = min(dic.values())  #找出数量最少的值
        for c in s:
            if dic[c] != Min:   #挑出非最少的即可
                res += c
        print(res)
    except:
        break

全部评论

相关推荐

给个offer灞:校友 是不是金die
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务