每日一道算法题 - LongestWord(easy-1)
生活随笔
收集整理的這篇文章主要介紹了
每日一道算法题 - LongestWord(easy-1)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
雖然都是很簡單的算法,每個都只需5分鐘左右,但寫起來總會遇到不同的小問題,希望大家能跟我一起每天進步一點點。
更多的小算法練習,可以查看我的文章。
規則
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語言,讓函數LongestWord(sen)獲取傳遞的sen參數并返回字符串中的最大單詞。如果有兩個或多個長度相同的單詞,則返回該長度的字符串中的第一個單詞。
ps: 忽略字符串中標點符號并假設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過濾字符串,并把字符串根據空格符轉換成字符串數組
2.通過循環把獲取字符串數組中的長度最長的字符串
總結
以上是生活随笔為你收集整理的每日一道算法题 - LongestWord(easy-1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 自带工具详解
- 下一篇: Freemaker FTL指令常用标签及