package main
import (
"bufio"
"fmt"
"os"
"unicode"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
var plaintext, ciphertext string
if scanner.Scan() {
plaintext = scanner.Text()
}
if scanner.Scan() {
ciphertext = scanner.Text()
}
encrypted := encrypt(plaintext)
decrypted := decrypt(ciphertext)
fmt.Println(encrypted)
fmt.Println(decrypted)
}
func encrypt(s string) string {
result := make([]rune, len(s))
for i, char := range s {
if unicode.IsLetter(char) {
switch char {
case 'Z':
result[i] = 'a'
case 'z':
result[i] = 'A'
default:
result[i] = char + 1
if unicode.IsUpper(char) {
result[i] = unicode.ToLower(result[i])
} else {
result[i] = unicode.ToUpper(result[i])
}
}
} else if unicode.IsDigit(char) {
if char == '9' {
result[i] = '0'
} else {
result[i] = char + 1
}
} else {
result[i] = char
}
}
return string(result)
}
func decrypt(s string) string {
result := make([]rune, len(s))
for i, char := range s {
if unicode.IsLetter(char) {
switch char {
case 'A':
result[i] = 'z'
case 'a':
result[i] = 'Z'
default:
result[i] = char - 1
if unicode.IsUpper(char) {
result[i] = unicode.ToLower(result[i])
} else {
result[i] = unicode.ToUpper(result[i])
}
}
} else if unicode.IsDigit(char) {
if char == '0' {
result[i] = '9'
} else {
result[i] = char - 1
}
} else {
result[i] = char
}
}
return string(result)
}
解题思路
算法分析
这道题的核心是字符映射转换。主要涉及:
- 字母加密:向后移动一位并改变大小写
- 数字加密:加1,9变为0
- 解密过程:加密的逆操作
- 边界处理:Z→a, z→A, 9→0, 0→9
代码实现思路
- 字符分类处理:使用unicode.IsLetter()判断字母使用unicode.IsDigit()判断数字其他字符保持不变
- 字母加密逻辑:边界情况:Z→a, z→A一般情况:向后移动一位并改变大小写使用unicode.ToUpper()和unicode.ToLower()转换大小写
- 数字加密逻辑:边界情况:9→0一般情况:加1
- 解密逻辑:字母:A→z, a→Z,其他向前移动并改变大小写数字:0→9,其他减1
时间复杂度分析
- 时间复杂度:O(n),其中n是字符串长度
- 空间复杂度:O(n),用于存储结果字符串
关键优化点
- 字符分类优化:使用unicode包的标准函数
- 内存分配优化:预分配结果数组
- 边界处理优化:特殊处理Z/z和9/0的情况
- 大小写转换优化:使用unicode包的内置函数
边界情况处理
- 字母边界:Z→a, z→A, A→z, a→Z
- 数字边界:9→0, 0→9
- 非字母数字字符:保持不变
- 空字符串:直接返回
算法特点
- 对称性:加密和解密是互逆操作
- 循环性:字母和数字都有循环特性
- 大小写转换:字母在移动时同时改变大小写
- 简单高效:单次遍历即可完成转换
这个问题的关键在于正确处理边界情况和实现对称的加密解密操作,特别是字母的大小写转换和数字的循环处理。

京公网安备 11010502036488号