Python 蓝桥杯 基础练习 完美的代价 贪心算法(正确代码)

# encoding = utf-8
# 开发者:xxx
# 开发时间: 0:21 
# "Stay hungry,stay foolish."

def huiwen(n, s):  # 判断能不能组成回文数
    temp_D = set()
    temp_S = 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 j in range(26):
            word = chr(ord('a') + j)
            # 统计了字符串 s 中特定字符(ASCII 值在 'a' 之后 j 个字符)出现的次数。
            if s.count(word) % 2 == 0:
                temp_D.add(word)  # 把个数是奇数个的字符放进temp
            else:
                temp_S.add(word)
            if len(temp_S) >= 2:
                print('Impossible')
                return False
        else:
            return True


# 贪心策略:
# 对于偶数的字符串,我们从第一个开始遍历,再倒序遍历出同样的,这个倒序遍历出来的序号,就是该移动的步数。我们把这个步数加到总步数之后,用pop弹出这个值。进行第二轮遍历。
# 遍历用n/2做大循环,用另一个序列做倒序序列,倒序序列更新后,原来的序列也要更新。
def step(n, s, s1, res):
    for i in range(n // 2):
        if s[i:].count(s[i]) != 1:  # 次数是否不等于 1
            temp = s1[:n - i].index(s[i])  # 是要移动的步数
            s1.pop(temp)
            res += temp
            s = s1[::-1]
        else:
            res += n // 2 - i
            s[i] = None
            s1 = s[::-1]
    return res


n = int(input())
s = list(input())
s1 = s[::-1]
res = 0
if huiwen(n, s):
    print(step(n, s, s1, res))

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值