题目链接

单词缩写

题目描述

对于一个单词,如果其字符个数大于或等于 10,则认为它是一个“长单词”。所有长单词都需要按以下规则进行缩写:

  • 写下单词的首字符。
  • 接着写下单词去掉首尾字符后剩余的字符个数。
  • 最后写下单词的尾字符。

例如,"localization" (长度12) 缩写为 "l10n"。

如果单词不是长单词(长度小于10),则保持原样。

给定 个单词,请对它们进行相应的处理并输出。

解题思路

这是一个简单的字符串处理和模拟问题。解题思路非常直接,只需对每个输入的单词应用题目给定的规则即可。

算法流程

  1. 读取输入

    • 首先读取整数 ,表示总共有 个单词需要处理。
    • 使用一个循环,从 1 到 ,依次读取每一个单词。
  2. 处理每个单词

    • 在循环的每一次迭代中,读取一个单词字符串(设为 word)。

    • 获取该单词的长度 length

    • 条件判断

      a. 如果 length >= 10,则该单词为长单词,需要缩写。

      • 获取首字符 word[0]
      • 获取尾字符 word[length - 1]
      • 计算中间部分的字符数 middle_count = length - 2
      • 将这三部分拼接成新的字符串,例如 word[0] + to_string(middle_count) + word[length - 1]
      • 输出缩写后的字符串。

      b. 如果 length < 10,则该单词不是长单词。

      • 直接输出原单词 word
  3. 循环与输出

    • 重复步骤 2,直到处理完所有 个单词。确保每个处理后的结果都换行输出。

代码

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n;
    cin >> n;
    while (n--) {
        string word;
        cin >> word;
        if (word.length() >= 10) {
            cout << word[0] << (word.length() - 2) << word.back() << endl;
        } else {
            cout << word << endl;
        }
    }

    return 0;
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            String word = sc.next();
            if (word.length() >= 10) {
                System.out.println("" + word.charAt(0) + (word.length() - 2) + word.charAt(word.length() - 1));
            } else {
                System.out.println(word);
            }
        }
    }
}
import sys

def solve():
    try:
        n_str = sys.stdin.readline()
        if not n_str: return
        n = int(n_str)
        
        for _ in range(n):
            word = sys.stdin.readline().strip()
            if len(word) >= 10:
                # 使用 f-string 格式化输出
                abbreviation = f"{word[0]}{len(word) - 2}{word[-1]}"
                print(abbreviation)
            else:
                print(word)

    except (IOError, ValueError):
        return

solve()

算法及复杂度

  • 算法:模拟、字符串处理

  • 时间复杂度,其中 是单词的总数, 是第 个单词的长度。我们需要读取所有单词的字符,这是总时间复杂度的主要部分。

  • 空间复杂度。我们需要空间来存储读入的最长的单个单词。