字符旋转

[题目链接](https://www.nowcoder.com/practice/e2034e10c9434a1f9c79810b9f09adbe)

思路

本题要求将字符串中每个字母按字母表循环前移一位,空格保持不变。

具体规则:

  • 小写字母:'b'~'z' 变为前一个字母,'a' 变为 'z'
  • 大写字母:'B'~'Z' 变为前一个字母,'A' 变为 'Z'
  • 空格:不做处理。

只需遍历字符串,对每个字符判断是否为字母,若是则做相应替换即可。对于边界情况 'a''A',需要特判循环到 'z''Z'

注意输入可能包含空格,需要用整行读取(getline / nextLine)。

代码

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

int main() {
    string s;
    getline(cin, s);
    for (char& c : s) {
        if (c >= 'a' && c <= 'z') {
            c = (c == 'a') ? 'z' : c - 1;
        } else if (c >= 'A' && c <= 'Z') {
            c = (c == 'A') ? 'Z' : c - 1;
        }
    }
    cout << s << endl;
    return 0;
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c >= 'a' && c <= 'z') {
                sb.append(c == 'a' ? 'z' : (char)(c - 1));
            } else if (c >= 'A' && c <= 'Z') {
                sb.append(c == 'A' ? 'Z' : (char)(c - 1));
            } else {
                sb.append(c);
            }
        }
        System.out.println(sb.toString());
    }
}

复杂度分析

  • 时间复杂度,其中 是字符串长度,遍历一次即可。
  • 空间复杂度(Java 中需要 StringBuilder);C++ 原地修改为