日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

每日一道算法题 - LongestWord(easy-1)

發(fā)布時(shí)間:2025/6/17 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 每日一道算法题 - LongestWord(easy-1) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

雖然都是很簡單的算法,每個(gè)都只需5分鐘左右,但寫起來總會遇到不同的小問題,希望大家能跟我一起每天進(jìn)步一點(diǎn)點(diǎn)。
更多的小算法練習(xí),可以查看我的文章。

規(guī)則

Using the JavaScript language, have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty.

使用JavaScript語言,讓函數(shù)LongestWord(sen)獲取傳遞的sen參數(shù)并返回字符串中的最大單詞。如果有兩個(gè)或多個(gè)長度相同的單詞,則返回該長度的字符串中的第一個(gè)單詞。
ps: 忽略字符串中標(biāo)點(diǎn)符號并假設(shè)sen不會為空。

測試用例

Input:"fun&!! time" Output:"time"Input:"I love dogs" Output:"love"

my code

function LongestWord(sen) { var senList = sen.match(/[a-z0-9]+/gi);var maxStr = ''for(var i=0; i<senList.length; i++) {if(maxStr.length < senList[i].length){maxStr = senList[i]}}// code goes here return maxStr; }

other code

code 1

function LongestWord(sen) { var arr = sen.match(/[a-z0-9]+/gi);var sorted = arr.sort(function(a, b) {return b.length - a.length;});return sorted[0]; }

code 2

function LongestWord(sen) { return sen.match(/[a-z0-9]+/gi).reduce((item, next) => item.length >= next.length ? item : next); }

思路

1.通過match過濾字符串,并把字符串根據(jù)空格符轉(zhuǎn)換成字符串?dāng)?shù)組
2.通過循環(huán)把獲取字符串?dāng)?shù)組中的長度最長的字符串

總結(jié)

以上是生活随笔為你收集整理的每日一道算法题 - LongestWord(easy-1)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。