JavaScript算法练习:找出字符串中最长的单词并输出其长度

今天的练习是找出字符串(可能是一句话)中最长的单词并且将其长度输出。这个算法其实就是让我们看看字符串中有多少个词,每个词有多少个字母,然后对这些词进行比较,找出字母数最多的那个词,并且返回这个最长字符数单词的长度。

实现上面描述的功能,同样先创建一个函数,比如findLongestWord(),并且给这个函数传入一个arr参数,这个arr是一个包含多个词的字符串。然后在函数通过以下几步来实现所需的功能:

  • 先把字符串arr转为数组
  • 将数组中的每个元素长度转换成一个新的数组
  • 将这个数组按由小到大排序
  • 取此数组中最后的数值,也就是最长的字符串
  • 将这个长度值返回

JavaScript方法

在写findLongestWord(str)函数实现文章开头所述的功能,根据上面的实现思路,将会大致用到下面几个有关于JavaScript点:

其中String.prototype.split()主要是用来将字符串str转换成数组arr。比如:

"May the force be with you".split(" ");
// ["May", "the", "force", "be", "with", "you"]

这里需要注意一点,在使用split()方法时,""中间得要有一个空格(" "),不然将会转成这样的一个数组:

"May the force be with you".split("");
// ["M", "a", "y", " ", "t", "h", "e", " ", "f", "o", "r", "c", "e", " ", "b", "e", " ", "w", "i", "t", "h", " ", "y", "o", "u"]

因为我们要做的是找出字符串str="May the force be with you"中最长的词,并且将其length输出来。那么我们需要的是将字符按单的而不是单独的字母来划分。因此要特别代码中split()的使用。

而其它几个都是具体写函数功能需要用的,比如for是用来做遍历的,而sort()方法用来对数组中的元素进行排序,而且这里都将是按从小到大的升序列来排列。

reduce()方法将数组中的每个值(从左到右)开始合并,最终返回一个值。而在这个方法中,将会调一个callback函数,这个函数的功能就是让我们找出数组中最大的一个值。有关于sort()reduce()更多的介绍,可以点击这里阅读

Math.max()方法可以很简单的从一个数组中取出最大的那个值:

Array.prototype.max = function () {
    return Math.max.apply({},this);
}
var arr = [1,45,23,3,6,2,7,234,56];
arr.max(); // 234

测试用例

通过测试用例是最好的检测方法,检测自己写的函数是否符合要求,下面提供几个测试用例:

  • findLongestWord("The quick brown fox jumped over the lazy dog")返回6
  • findLongestWord("May the force be with you")返回5
  • findLongestWord("Google do a barrel roll")返回6
  • findLongestWord("What is the average airspeed velocity of an unladen swallow")返回8
  • findLongestWord("What if we try a super-long word such as otorhinolaryngology")返回19

实现方法

下面提供了几种实现findLongestWord(str)的方法,不过这几种方法简单的可以分为for循环的、sort()reduce()的。感兴趣的同学可以看看。(代码中有相关备注)

for循环

function findLongestWord(str) {
    // 第1步:将传给str的值"May the force be with you"转换成数组
    var array = str.split(' ');

    // 得到数组 ["May", "the", "force", "be", "with", "you"]
    var longest = 0;

    // 第2步:对数组array做遍历,并且将符合条件的值赋值给longest
    for (var i = 0; i < array.length; i++) { 
        // array.length = 6

        if (array[i].length > longest) {
            // 如果为true,longest值为array[i].length;
            longest = array[i].length;
        }
    }
    /* 
     * array = ["May", "the", "force", "be", "with", "you"]
     * array.length = 6
     *
     * 遍历次数  i = ?  i < array.length  i++   array[i].length  longest   array[i].length > longest   longest= array[i].length
     * 1st       0     yes               1     "May".length=3      0        3 > 0 => yes                  3
     * 2nd       1     yes               2     "the".length=3      3        3 > 3 => no                   3
     * 3rd       2     yes               3     "force".length=5    3        5 > 3 => yes                  5
     * 4th       3     yes               4     "be".length=2       5        2 > 5 => no                   5
     * 5th       4     yes               5     "with".length=4     5        4 > 5 => no                   5
     * 6th       5     yes               6     "you".length=3      5        3 > 5 => no                   5
     * 7th       6     no
     * End Loop
     */
    // 第3步:输出最长词的长度
    return longest; // 5
}

你可以把前面的测试示例都运行一回,看看是否得到的值是正确的,如果不是,那就要检查一下代码是不是哪里出错了。除了上述的方法之外,还可以for循环之后,通过Math.max()直接将数组arrNum中的最大值取出。如下所示:

function findLongestWord(str) {
    // 第1步:将传给str的值为:"May the force be with you"转成数组
    var arr = str.split(" "); 

    // 得到数组 arr = ["May", "the", "force", "be", "with", "you"]
    var arrNum = [];

    //  第2步: 对数组arr做遍历
    for (var i = 0; i < arr.length; i++) { // arr.length = 6
        // 将数组arr中每个元素的长度length放到一个新数组arrNum中
        arrNum.push(arr[i].length);
        /*
         * 遍历次数  i = ?  i < arr.length  i++  arr[i]  arr[i].length  arrNum
         * 1st      0      yes              1    "May"     3           [3]
         * 2nd      1      yes              2    "the"     3           [3,3]
         * 3rd      2      yes              3    "force"   5           [3,3,5]
         * 4th      3      yes              4    "be"      2           [3,3,5,2]
         * 5th      4      yes              5    "with"    4           [3,3,5,2,4]
         * 6th      5      yes              6    "you"     3           [3,3,5,2,4,3]
         * 7th      6      no
         * End Loop
         */
    }

    // 第3步: 通过Math.max()取出数组arrNum中最大值,并且输出
    return Math.max.apply(null, arrNum); // 5
}

sort()方法

function findLongestWord(str) {
    // 第1步:将传给str的值为:"May the force be with you"转成数组
    var strArr = str.split(" "); 
    // 得到数组strArr=["May", "the", "force", "be", "with", "you"]
    var numArr = [];
    var sortArr = [];

    // 第2步:对strArr数组做遍历,并把数组中每个词的length放到新数组numArr中
    for (var i = 0; i < strArr.length; i++) { 
        numArr[i] = strArr[i].length; 
    }
    // 新数组:numArr = [3,3,5,2,4,3]

    // 第3步,使用sort()对数组numArr排序,由小到大
    sortArr = numArr.sort(function compare(a, b) {
        return a - b;
    });
    // 排序后的数组: sortArr = [2,3,3,3,4,5]

    // 第4步:通过pop()取到数组sortArr中最后一个值,赋值给longestWord
    var longestWord = sortArr.pop(); //5

    // 第5步,输出longestWord
    return longestWord; // 5
}

或者:

function findLongestWord(str) {
    // 第1步:将传给str的值为:"May the force be with you"转成数组
    var arr = str.split(' '); 
    // 得到数组 arr = ["May", "the", "force", "be", "with", "you"]

    // 第2步: 通过sort()将数组arr按由小到大排序
    arr = arr.sort(function(a, b) {
        return a.length - b.length;
    });
    /*
     *     a          b     b.length   a.length      arr
     *   "May"     "the"      3         3        ["May","the"]
     *   "the"     "force"    5         3        ["May","the","force"]
     *   "force"    "be"      2         5        ["be","May","the","force"]
     *   "be"       "with"    4         2        ["be","May","the","with","force"]
     *   "with"     "you"     3         4        ["be","May","the","you","with","force"]
     */
    // 最长的字符排在数组最后

    // 第3步:获取数组最长字符的长度
    var longestString = arr.pop().length; // 5

    // 第4步:返回最长字符的长度
    return longestString; // 5
}

reduce()方法

function findLongestWord(str) {
    // 第1步:将传给str的值为:"May the force be with you"转成数组
    var strSplit = str.split(' ');

    // 得到数组 strSplit = ["May", "the", "force", "be", "with", "you"];

    // 第2步使用reduce方法,取到strSplit数组中最长的元素
    var longestWord = strSplit.reduce(function(longest, currentWord) {
        return currentWord.length > longest.length ? currentWord : longest;
    }, "");
    // 取到最长的元素longestWord = "force"
    /*
     * strSplit = ["May", "the", "force", "be", "with", "you"];
     * currentWord   longest   currentWord.length   longest.length   currentWord.length > longest.length  longestWord
     *  "May"         ""            3                   0                  yes                               "May"
     *  "the"         "May"         3                   3                  no                                "May"
     *  "force"       "May"         5                   3                  yes                               "force"
     *  "be"          "force"       2                   5                  no                                "force"
     *  "with"        "force"       4                   5                  no                                "force"
     *  "you"         "force"       3                   5                  no                                "force"
     */

    // 第3步. 返回longestWord的length
    return longestWord.length; // 5
    // longestWord.length => "force".length => 5
}

也可以使用reduce()方法和Math.max()方法配合使用:

function findLongestWord(str) {
    // 第1步:将传给str的值为:"May the force be with you"转成数组
    var strSplit = str.split(' ');
    // 得到数组 strSplit = ["May", "the", "force", "be", "with", "you"];

    // 第2步使用reduce方法,取到strSplit数组中最长的元素的length,并且返回
    return strSplit.reduce(function(longest, currentWord) {
        return Math.max(longest, currentWord.length)
    }, 0); // "force".length = >5
}

总结

文章中通过几种不同的方法实现了:找出字符串(可能是一句话)中最长的单词并且将其长度输出。主要使用了forsort()reduce()方法,当然在具体实现功能过程中,还运用到了JavaScript中的split()pop()Math.max()等方法。如果您有更好的方案欢迎在下面的评论中与我们分享。

扩展阅读

大漠

常用昵称“大漠”,W3CPlus创始人,目前就职于手淘。对HTML5、CSS3和Sass等前端脚本语言有非常深入的认识和丰富的实践经验,尤其专注对CSS3的研究,是国内最早研究和使用CSS3技术的一批人。CSS3、Sass和Drupal中国布道者。2014年出版《图解CSS3:核心技术与案例实战》。

如需转载,烦请注明出处:http://www.w3cplus.com/javascript/find-the-longest-word-solution.html

返回顶部