题解 | #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
【牛客站内】华为机试题解 文章被收录于专栏
【牛客站内】 分享个人刷题的思路和解法