每日一道算法题 - 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语言,让函数LongestWordsen)获取传递的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.经过循环把获取字符串数组中的长度最长的字符串测试

相关文章
相关标签/搜索