最长最短单词

GitHub跳转原题关系图返回列表

顺序扫描一行句子,把连续字母段看作单词,取第一个最长单词和第一个最短单词。

OJ: roj

题目 ID: 1143

难度:入门

标签:字符串模拟

创建: 2026-09-29 20:40

更新: 2026-10-05 03:20

题目描述

输入一行句子(不超过 200 个单词,每个单词长度不超过 100),只含字母、空格和逗号,空格和逗号都是单词之间的间隔。输出第一行是第一个最长的单词,第二行是第一个最短的单词。样例输入 I am studying Programming language C in Peking University,输出 Programming 和 I。

思路

顺序扫描整行,把每一段连续字母当作一个单词;只有严格更长时才替换最长单词,只有严格更短时才替换最短单词,长度相等的保留先出现的那个,正好得到"第一个最长/第一个最短"。

参考代码

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-09-29 20:40
# update_at: 2026-09-29 20:40

import re
import sys


def solve() -> None:
    # 题面是一整行句子,词与词之间靠空格和逗号分隔:必须原样保留这些分隔符
    # 才能用正则按"非字母"切词,所以整篇读入,而不是按空白 token 顺序消费。
    text = sys.stdin.read()
    words: list[str] = re.findall(r"[A-Za-z]+", text)
    print(max(words, key=len))
    print(min(words, key=len))


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-05 03:20
 * update_at: 2026-10-05 03:20
 */

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

string line;          // 整行句子,包含字母、空格和逗号
string longest_word;  // 第一个最长的单词
string shortest_word; // 第一个最短的单词

// 判断一个字符是否为英文字母
bool is_letter(char ch) {
    return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
}

int main() {
    getline(cin, line);

    // 扫描整行,把连续字母段看成一个单词;只有严格更长/更短才更新,
    // 这样留下的自然是第一个最长、第一个最短的单词。
    ll i = 0;
    ll len = line.size();
    while (i < len) {
        if (!is_letter(line[i])) {
            i++;
            continue;
        }
        string word = "";
        while (i < len && is_letter(line[i])) {
            word += line[i];
            i++;
        }
        if (word.size() > longest_word.size()) {
            longest_word = word;
        }
        if (shortest_word == "" || word.size() < shortest_word.size()) {
            shortest_word = word;
        }
    }

    cout << longest_word << "\n";
    cout << shortest_word << "\n";
    return 0;
}