You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

英文字符串首尾转换问题:反向位置字母替换实现需求

反向字母表替换字符串解决方案

给定仅由英文字母组成的字符串,我们需要将每个字母替换为字母表反向排序后同位置的字母(小写对应小写,大写对应大写),比如a↔z、b↔y、A↔Z等。

核心逻辑

利用ASCII码的数值关系计算反向字符:

  • 小写字母:chr(ord('z') - ord(c) + ord('a'))
  • 大写字母:chr(ord('Z') - ord(c) + ord('A'))

Python 实现

def reverse_alphabet(s):
    result = []
    for char in s:
        if char.islower():
            reversed_char = chr(ord('z') - ord(char) + ord('a'))
            result.append(reversed_char)
        elif char.isupper():
            reversed_char = chr(ord('Z') - ord(char) + ord('A'))
            result.append(reversed_char)
        else:
            # 题目限定仅英文字母,此处可直接保留字符
            result.append(char)
    return ''.join(result)

# 测试用例
print(reverse_alphabet("HelloWorld"))  # 输出 "SvoolDliow"
print(reverse_alphabet("abcXYZ"))      # 输出 "zyxCBA"

JavaScript 实现

function reverseAlphabet(str) {
    let output = [];
    for (const char of str) {
        if (char >= 'a' && char <= 'z') {
            const reversedChar = String.fromCharCode('z'.charCodeAt(0) - char.charCodeAt(0) + 'a'.charCodeAt(0));
            output.push(reversedChar);
        } else if (char >= 'A' && char <= 'Z') {
            const reversedChar = String.fromCharCode('Z'.charCodeAt(0) - char.charCodeAt(0) + 'A'.charCodeAt(0));
            output.push(reversedChar);
        } else {
            output.push(char);
        }
    }
    return output.join('');
}

# 测试用例
console.log(reverseAlphabet("HelloWorld")); // 输出 "SvoolDliow"
console.log(reverseAlphabet("abcXYZ"));     // 输出 "zyxCBA"

逻辑说明

遍历字符串中的每个字符:

  1. 判断字符是小写还是大写
  2. 通过ASCII码的差值计算反向位置的字符
  3. 将所有转换后的字符拼接成最终字符串

内容的提问来源于stack exchange,提问作者mayank damor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 20:35:27