校招算法笔面试 | 华为机试-字符串加密

题目## 题目

题目链接

解题思路

  1. 加密规则:
    • 英文字母:字母变为其后一个字母,同时改变大小写
    • 数字:数字加1,9变为0
    • 其他字符不变
  2. 解密规则:
    • 加密的逆过程
    • 英文字母:字母变为其前一个字母,同时改变大小写
    • 数字:数字减1,0变为9

代码

def encrypt(s):
    result = []
    for c in s:
        if c.isalpha():
            # 处理字母
            is_upper = c.isupper()
            # 获取下一个字母,注意z/Z的特殊情况
            next_char = chr((ord(c.lower()) - ord('a') + 1) % 26 + ord('a'))
            # 改变大小写
            result.append(next_char.upper() if not is_upper else next_char.lower())
        elif c.isdigit():
            # 处理数字
            result.append(str((int(c) + 1) % 10))
        else:
            result.append(c)
    return ''.join(result)

def decrypt(s):
    result = []
    for c in s:
        if c.isalpha():
            # 处理字母
            is_upper = c.isupper()
            # 获取前一个字母,注意a/A的特殊情况
            prev_char = chr((ord(c.lower()) - ord('a') - 1) % 26 + ord('a'))
            # 改变大小写
            result.append(prev_char.upper() if not is_upper else prev_char.lower())
        elif c.isdigit():
            # 处理数字
            result.append(str((int(c) - 1) % 10))
        else:
            result.append(c)
    return ''.join(result)

while True:
    try:
        s1 = input()
        s2 = input()
        print(encrypt(s1))
        print(decrypt(s2))
    except EOFError:
        break
#include <iostream>
#include <string>
using namespace std;

string encrypt(string s) {
    string result;
    for (char c : s) {
        if (isalpha(c)) {
            // 处理字母
            bool isUpper = isupper(c);
            // 获取下一个字母
            char nextChar = (tolower(c) - 'a' + 1) % 26 + 'a';
            // 改变大小写
            result += isUpper ? tolower(nextChar) : toupper(nextChar);
        }
        else if (isdigit(c)) {
            // 处理数字
            result += ((c - '0' + 1) % 10) + '0';
        }
        else {
            result += c;
        }
    }
    return result;
}

string decrypt(string s) {
    string result;
    for (char c : s) {
        if (isalpha(c)) {
            // 处理字母
            bool isUpper = isupper(c);
            // 获取前一个字母
            char prevChar = (tolower(c) - 'a' - 1 + 26) % 26 + 'a';
            // 改变大小写
            result += isUpper ? tolower(prevChar) : toupper(prevChar);
        }
        else if (isdigit(c)) {
            // 处理数字
            result += ((c - '0' - 1 + 10) % 10) + '0';
        }
        else {
            result += c;
        }
    }
    return result;
}

int main() {
    string s1, s2;
    while (getline(cin, s1) && getline(cin, s2)) {
        cout << encrypt(s1) << endl;
        cout << decrypt(s2) << endl;
    }
    return 0;
}
import java.util.*;

public class Main {
    private static String encrypt(String s) {
        StringBuilder result = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (Character.isLetter(c)) {
                // 处理字母
                boolean isUpper = Character.isUpperCase(c);
                // 获取下一个字母
                char nextChar = (char)((Character.toLowerCase(c) - 'a' + 1) % 26 + 'a');
                // 改变大小写
                result.append(isUpper ? Character.toLowerCase(nextChar) : Character.toUpperCase(nextChar));
            }
            else if (Character.isDigit(c)) {
                // 处理数字
                result.append((c - '0' + 1) % 10);
            }
            else {
                result.append(c);
            }
        }
        return result.toString();
    }
    
    private static String decrypt(String s) {
        StringBuilder result = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (Character.isLetter(c)) {
                // 处理字母
                boolean isUpper = Character.isUpperCase(c);
                // 获取前一个字母
                char prevChar = (char)((Character.toLowerCase(c) - 'a' - 1 + 26) % 26 + 'a');
                // 改变大小写
                result.append(isUpper ? Character.toLowerCase(prevChar) : Character.toUpperCase(prevChar));
            }
            else if (Character.isDigit(c)) {
                // 处理数字
                result.append((c - '0' - 1 + 10) % 10);
            }
            else {
                result.append(c);
            }
        }
        return result.toString();
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String s1 = sc.nextLine();
            String s2 = sc.nextLine();
            System.out.println(encrypt(s1));
            System.out.println(decrypt(s2));
        }
    }
}

算法及复杂度

  • 算法:字符串处理
  • 时间复杂度: O ( n ) \mathcal{O}(n) O(n),其中n为字符串长度
  • 空间复杂度: O ( n ) \mathcal{O}(n) O(n),需要存储结果字符串

题目链接

解题思路

  1. 根据密钥构建加密字母表:

    • 去除密钥中重复字母,只保留第一次出现的字母
    • 将处理后的密钥放在新字母表的开头
    • 将剩余未出现在密钥中的字母按字母表顺序依次加入
  2. 使用新的字母表进行加密:

    • 对于明文中的每个字母,在原始字母表中找到其位置
    • 用新字母表中相同位置的字母替换

代码

#include <iostream>
#include <string>
#include <unordered_set>
#include <algorithm>
using namespace std;

string encrypt(string key, string text) {
    string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    transform(key.begin(), key.end(), key.begin(), ::toupper);
    
    // 构建新密码表
    string cipher;
    unordered_set<char> used;
    
    // 处理密钥
    for (char c : key) {
        if (used.find(c) == used.end() && alphabet.find(c) != string::npos) {
            cipher += c;
            used.insert(c);
        }
    }
    
    // 添加剩余字母
    for (char c : alphabet) {
        if (used.find(c) == used.end()) {
            cipher += c;
            used.insert(c);
        }
    }
    
    // 加密
    string result;
    transform(text.begin(), text.end(), text.begin(), ::tolower);
    for (char c : text) {
        if (isalpha(c)) {
            int idx = c - 'a';
            result += tolower(cipher[idx]);
        } else {
            result += c;
        }
    }
    
    return result;
}

int main() {
    string key, text;
    getline(cin, key);
    getline(cin, text);
    cout << encrypt(key, text) << endl;
    return 0;
}
import java.util.*;

public class Main {
    public static String encrypt(String key, String text) {
        String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        key = key.toUpperCase();
        
        // 构建新密码表
        StringBuilder cipher = new StringBuilder();
        Set<Character> used = new HashSet<>();
        
        // 处理密钥
        for (char c : key.toCharArray()) {
            if (!used.contains(c) && alphabet.indexOf(c) != -1) {
                cipher.append(c);
                used.add(c);
            }
        }
        
        // 添加剩余字母
        for (char c : alphabet.toCharArray()) {
            if (!used.contains(c)) {
                cipher.append(c);
                used.add(c);
            }
        }
        
        // 加密
        StringBuilder result = new StringBuilder();
        for (char c : text.toLowerCase().toCharArray()) {
            if (Character.isLetter(c)) {
                int idx = c - 'a';
                result.append(Character.toLowerCase(cipher.charAt(idx)));
            } else {
                result.append(c);
            }
        }
        
        return result.toString();
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String key = sc.nextLine();
        String text = sc.nextLine();
        System.out.println(encrypt(key, text));
    }
}
def encrypt(key, text):
    # 构建加密字母表
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    key = key.upper()
    
    # 去除密钥中的重复字母
    new_key = ''
    for c in key:
        if c not in new_key:
            new_key += c
    
    # 构建新的字母表
    cipher = ''
    for c in new_key:
        if c not in cipher and c in alphabet:
            cipher += c
    for c in alphabet:
        if c not in cipher:
            cipher += c
            
    # 加密过程
    result = ''
    for c in text.lower():
        if c.isalpha():
            # 找到原字母在原始字母表中的位置
            idx = ord(c) - ord('a')
            # 用新字母表中对应位置的字母替换
            result += cipher[idx].lower()
        else:
            result += c
            
    return result

# 处理输入
key = input()
text = input()
print(encrypt(key, text))

算法及复杂度

  • 算法:字符串处理 + 映射替换
  • 时间复杂度: O ( n ) \mathcal{O}(n) O(n),其中 n 为明文长度
  • 空间复杂度: O ( 1 ) \mathcal{O}(1) O(1),因为字母表大小是固定的(26个字母)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值