题解 | 小红的字符串

小红的字符串

https://www.nowcoder.com/practice/f9738786c00a40a2b7ddf6c82c1a59b1

while True:
    try:
        s = input()
        if len(s) % 2 == 0:
            half_index = len(s) // 2 - 1
            # print(half_index)
            s_1 = s[:half_index + 1]
            s_2 = s[:half_index:-1]
            # print(s_1)
            # print(s_2)
            new_s = list(zip(s_1, s_2))
            # print(new_s)
            total = 0
            for i, j in new_s:
                # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 25 16 17 18 19 20 21 22 23 24 25 26
                # a b c d e f g h i j  k  l  m  n  o  p  q  r  s  t  u  v  w  x  y  z
                # 进行最小间距取值,abs(ord(i)-ord(j)), 26-abs(ord(i)-ord(j))中取小的
                count = min(abs(ord(i) - ord(j)), 26 - abs(ord(i) - ord(j)))
                total += count
            print(total)

        else:
            half_index = len(s) // 2
            # print(half_index)
            s_1 = s[:half_index + 1]
            s_2 = s[:half_index - 1:-1]
            # print(s_1)
            # print(s_2)
            new_s = list(zip(s_1, s_2))
            # print(new_s)
            total = 0
            for i, j in new_s:
                count = min(abs(ord(i) - ord(j)), 26 - abs(ord(i) - ord(j)))
                total += count
            print(total)
    except Exception as e:
        break

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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