第二行给出 A~Z 的 26 位编码表:对第一行逐字符查表,大写字母换成 T[c-A],空格等表外字符原样输出,一趟 O(n) 扫完。
OJ: roj
题目 ID: 10027
难度:普及
标签:入门字符串python
创建: 2026-10-02 18:54
更新: 2026-10-04 22:08
题目描述
给定一行字符串
样例 1 输入 HPC PJVYMIY / BLMRGJIASOPZEFDCKWYHUNXQTV,输出 ACM CONTEST;样例 2 输入 FDY GAI BG UKMY / KIMHOTSQYRLCUZPAGWJNBVDXEF,输出 THE SKY IS BLUE。
思路
对每个大写字母
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-10-02 18:56
# update_at: 2026-10-02 19:07
import sys
def solve() -> None:
text, table, *_ = sys.stdin.read().split("\n") # 第一行待编码串,第二行 A~Z 编码表
# str.maketrans 把 A~Z 逐位绑定到表中字母;空格不在表里,原样保留。
# translate 在 C 层逐字符查表,O(n) 一次扫完,等价于逐字符 if 的朴素循环。
print(text.translate(str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", table)))
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-04 22:06
* update_at: 2026-10-04 22:06
*/
#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
string text; // 第一行:待编码的字符串,只含大写字母和空格
string table; // 第二行:table[i] 表示字母 'A' + i 编码后变成的字母
int main() {
getline(cin, text);
getline(cin, table);
ll len = text.size();
for (ll i = 0; i < len; i++) {
char c = text[i];
if (c >= 'A' && c <= 'Z') {
cout << table[c - 'A']; // 大写字母按下标 c-'A' 查表
} else {
cout << c; // 空格等非大写字母原样输出
}
}
cout << "\n";
return 0;
}