题解 | #HJ29 字符串加解密#

字符串加解密

https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a

方法1-利用ASCII码表

1.1 常规思路

def encrypt(s):
    li = list(s)
    for i in range(len(li)):
        if li[i].islower():
            if ord(li[i]) < ord("z"):
                li[i] = chr(ord(li[i]) + 1).upper()
            else:
                li[i] = "A"
        elif li[i].isupper():
            if ord(li[i]) < ord("Z"):
                li[i] = chr(ord(li[i]) + 1).lower()
            else:
                li[i] = "a"
        elif li[i].isdigit():
            if int(li[i]) < 9:
                li[i] = str(int(li[i]) + 1)
            else:
                li[i] = "0"
    return "".join(li)


def decrypt(s):
    li = list(s)
    for i in range(len(li)):
        if li[i].islower():
            if ord(li[i]) > ord("a"):
                li[i] = chr(ord(li[i]) - 1).upper()
            else:
                li[i] = "Z"
        elif li[i].isupper():
            if ord(li[i]) > ord("A"):
                li[i] = chr(ord(li[i]) - 1).lower()
            else:
                li[i] = "z"
        elif li[i].isdigit():
            if int(li[i]) > 0:
                li[i] = str(int(li[i]) - 1)
            else:
                li[i] = "9"
    return "".join(li)


s1 = input()
s2 = input()
print(encrypt(s1))
print(decrypt(s2))

1.2 优化:通过函数转换大小写

def encrypt(s):
    li = list(s)
    case = lambda x: x.upper() if x.islower() else x.lower()
    for i in range(len(li)):
        if li[i].isalpha():
            if ord(li[i].lower()) < ord("z"):
                li[i] = case(chr(ord(li[i]) + 1))
            else:
                li[i] = case(chr(ord(li[i]) - 25))
        elif li[i].isdigit():
            if ord(li[i].lower()) < ord("9"):
                li[i] = case(chr(ord(li[i]) + 1))
            else:
                li[i] = case(chr(ord(li[i]) - 9))
    return "".join(li)


def decrypt(s):
    li = list(s)
    for i in range(len(li)):
        if li[i].isalpha():
            if ord(li[i].lower()) > ord("a"):
                li[i] = case(chr(ord(li[i]) - 1))
            else:
                li[i] = case(chr(ord(li[i]) + 25))
        elif li[i].isdigit():
            if ord(li[i].lower()) > ord("0"):
                li[i] = case(chr(ord(li[i]) - 1))
            else:
                li[i] = case(chr(ord(li[i]) + 9))
    return "".join(li)


s1 = input()
s2 = input()
print(encrypt(s1))
print(decrypt(s2))

方法2-模运算限定区间

def shift_char(c, shift, start, end):
    # 通过模运算确保结果在start和end之间循环
    # 示例:chr((ord('z') - ord('a') + 1) % 26 + ord('a')) -> 'a'
    shifted = chr((ord(c) - start + shift) % (end - start + 1) + start)
    return shifted.lower() if c.isupper() else shifted.upper()

def process_string(s, shift):
    result = ''
    for char in s:
        if char.islower():
            result += shift_char(char, shift, ord('a'), ord('z'))
        elif char.isupper():
            result += shift_char(char, shift, ord('A'), ord('Z'))
        elif char.isdigit():
            result += shift_char(char, shift, ord('0'), ord('9'))
        else:
            result += char
    return result

while True:
    try:
        print(process_string(input(), 1))
        print(process_string(input(), -1))
    except:
        break

方法3-字典映射

def process(string, shift):
    L1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    L2 = 'BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza1234567890'
    encrypt = dict(zip(L1, L2))
    decrypt = dict(zip(L2, L1))
    mapping = {
        1: encrypt,
        -1: decrypt
    }
    return ''.join([mapping[shift][c] for c in string])


while True:
    try:
        print(process(input(), 1))
        print(process(input(), -1))
    except:
        break

【牛客站内】华为机试题解 文章被收录于专栏

【牛客站内】 分享个人刷题的思路和解法

全部评论

相关推荐

jack_miller:我给我们导员说我不在这里转正,可能没三方签了。导员说没事学校催的时候帮我想办法应付一下
点赞 评论 收藏
分享
点赞 评论 收藏
分享
11-24 00:11
已编辑
广东工业大学 算法工程师
避雷深圳&nbsp;&nbsp;yidao,试用期&nbsp;6&nbsp;个月。好嘛,试用期还没结束,就直接告诉你尽快找下一家吧,我谢谢您嘞
牛客75408465号:笑死,直属领导和 hr 口径都没统一,各自说了一些离谱的被裁理由,你们能不能认真一点呀,哈哈哈哈哈😅😅😅
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务