把字符串视作循环序列,将每个字符与后继字符 ASCII 值之和转为新字符。
OJ: noi_openjudge
题目 ID: ch0107-05
难度:入门
标签:字符串模拟python
日期: 2026-07-30 23:01
题意
构造亲朋字符串:每个位置输出当前字符与下一个字符 ASCII 值之和,最后一个字符与第一个配对。
思路
text[1:] + text[:1] 把首字符接到末尾,形成后继字符序列。两串 zip 后对每对字符取 ord 之和,再用 chr 转回字符。
代码
Python代码
python
text = input()
result = [chr(ord(left) + ord(right)) for left, right in zip(text, text[1:] + text[:1])]
print("".join(result))C++代码
cpp
#include <cstdio>
#include <cstring>
char str[500];
int idx = 1;
int main(){
char t;
while( scanf("%c",&t) != EOF){
if( t == '\n' || t == '\r')
break;
str[idx] = t;
idx++;
}
idx--;
int i;
for (i=1;i<idx;i++){
//printf("%c %d\n",str[i],str[i]);
printf("%c",str[i]+str[i+1]);
}
printf("%c",str[1]+str[idx]);
return 0;
}复杂度
时间复杂度和额外空间复杂度均为
总结
循环相邻关系可通过“去首后接首”的字符串构造直接表达。