每日一道算法题 - LongestWord(easy-1)
雖然都是很簡單的算法,每個(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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 自带工具详解
- 下一篇: Freemaker FTL指令常用标签及