蓝桥杯—基础训练 python完美的代价

def check(n, s):  #检查是否是回文数
    temp = set()
    if n%2 == 0: 
        for i in range(26):
            if s.count(chr(ord('a')+i)) % 2 != 0:  #出现不可匹配,不是回文数
                print("Impossible")
                return False
        else:
            return True
    else:
        for i in range(26):
            if s.count(chr(ord('a') + i)) % 2 != 0:  #不可匹配添加到集合里
                temp.add(chr(ord('a') + i))
            if len(temp) > 1:  #如果多个不可匹配,不是回文数
                print("Impossible")
                return False
        else:
            return True
                
def step(n, s, res):
    for i in range(n//2): #减少无效循环
        if s[i:].count(s[i]) != 1: #成对
            temp = s[::-1].index(s[i]) #倒叙下标就是移动步数
            s.pop(len(s) - temp - 1)  #弹出该匹配成功
            res += temp #添加到总部数
        else:
            res += n//2 - i 
    return res
        

n = int(input())
s = list(input())
res = 0
if check(n, s):
    print(step(n, s, res))
    
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值