最长单词2

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

去掉句末标点后逐词扫描,严格更长才更新,保留并列时的第一个最长单词。

OJ: roj

题目 ID: 1149

难度:入门

标签:字符串python

创建: 2026-09-29 20:49

更新: 2026-10-05 03:33

题目描述

输入一行以 . 结尾的简单英文句子(长度不超过 500),单词之间用单个空格分隔。去掉句末标点后,输出最长的单词;若多个单词并列最长,输出第一个。

思路

先去掉句末的 .,然后逐个字符拼出单词。维护当前最长单词及其长度,仅当新单词长度严格更大时才更新,这样并列时自然保留最先出现者。

参考代码

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

import sys


def longest_word(sentence: str) -> str:
    """取最长单词:max 只在新元素严格更长时才替换,天然保留并列时最先出现的那个。"""
    words = sentence.split()          # 单空格分隔,split() 顺带吞掉两端空白
    return max(words, key=len)        # 比较键只有长度,首个最长单词胜出


def solve() -> None:
    sentence = sys.stdin.read().strip().removesuffix('.')  # 句末 '.' 是标点不是单词
    print(longest_word(sentence))


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:32
 * update_at: 2026-10-05 03:32
 */
#include <iostream>
#include <string>
using namespace std;

typedef long long ll;

string s;            // 读入的整行句子
string best_word;    // 当前找到的最长单词
ll best_len;         // 当前最长单词的长度

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    // 读入整行,句末 '.' 是标点不是单词的一部分,先去掉
    getline(cin, s);
    if (!s.empty() && s.back() == '.') s.pop_back();

    string word;     // 当前正在拼的单词
    for (size_t i = 0; i < s.size(); i++) {
        if (s[i] == ' ') {
            if (!word.empty()) {
                // 严格更长才替换,相等时保留先到者
                if ((ll) word.size() > best_len) {
                    best_len = (ll) word.size();
                    best_word = word;
                }
                word.clear();
            }
        } else {
            word.push_back(s[i]);
        }
    }
    // 句尾最后一个单词(如果输入不是以空格结尾)
    if (!word.empty()) {
        if ((ll) word.size() > best_len) {
            best_len = (ll) word.size();
            best_word = word;
        }
    }

    cout << best_word << "\n";
    return 0;
}