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

如何实现LongestWord(sen)函数以返回字符串中的最长单词

LongestWord 函数实现方案

功能规则

  • 接收字符串参数sen,返回字符串中最长的单词
  • 若存在2个及以上长度相同的最长单词,返回首个出现的对应长度单词
  • 处理过程自动忽略所有标点符号,输入保证非空
  • 单词允许包含数字

实现思路

  1. 预处理输入字符串:过滤所有非字母、非数字、非空格的标点字符,避免标点影响单词长度计算
  2. 将处理后的字符串按空格分割为单词数组,自动过滤连续空格产生的空值
  3. 遍历单词数组,记录最长单词,长度相同时保留先出现的单词
  4. 返回最终记录的最长单词

JavaScript 实现代码

function LongestWord(sen) {
  // 过滤标点符号,仅保留字母、数字、空格
  const cleanedSen = sen.replace(/[^a-zA-Z0-9\s]/g, '')
  // 分割为单词数组,过滤连续空格产生的空字符串
  const wordList = cleanedSen.split(/\s+/).filter(word => word)
  // 遍历查找第一个最长单词
  let longest = wordList[0]
  for (const word of wordList) {
    if (word.length > longest.length) {
      longest = word
    }
  }
  return longest
}

Python 实现代码

import re

def LongestWord(sen):
    # 过滤标点符号,仅保留字母、数字、空格
    cleaned_sen = re.sub(r'[^a-zA-Z0-9\s]', '', sen)
    # 分割为单词数组,自动忽略连续空格
    word_list = cleaned_sen.split()
    # 按单词长度降序排序,相同长度保留原顺序,取第一个元素
    word_list.sort(key=lambda x: len(x), reverse=True)
    return word_list[0]

测试验证

  • 输入 Hello world123 567,输出 world123,符合预期
  • 输入 Today is a beautiful, sunny day!,过滤标点后分割为 ['Today','is','a','beautiful','sunny','day'],输出最长的第一个单词 beautiful
  • 输入 test1 test2 test3,三个单词长度相同,输出首个出现的 test1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:15:03