solution on Find the longest word and return its length

solution on Find the longest word and return its length

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

步骤分析

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

JavaScript方法

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

  • for
  • String.prototype.split()
  • Array.prototype.sort()
  • Array.prototype.reduce()
  • Math.max()
  • Array.prototype.pop()

其中 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"]

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

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

测试用例

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

  • 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

实现方法

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){
// 1st:将传给str的值为:"May the force be with you"转成数组

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

// 2st:对数组arr做遍历
for(var i=o; i<arr.length; i++){
// 讲数组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 
     */
 }      
 
 // 3st:通过Math.max()取出数组arrNum中最大值,并且输出
 return Math.max.apply(null,arrNum);//5
 }

sort()方法

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

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

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

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

// 5st: 输出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){
// 1st: 将传给str的值为:"May the force be with you"转成数组
var strSplit=str.split(' ');

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

// 2st: 使用reduce方法,取得strSplit数组中最长的元素
var longestWord = strSplit.reduce(function(longest,currentWord){
return currentWord.length > longestWord ? current : 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){
// 1st: 将传给str的值为:"May the force be with you"转成数组
var strSplit = str.split(' ');
// 得到数组strSplit = ["May", "the", "force", "be", "with", "you"];

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

总结

文章中通过几种不同的方法实现了:找出字符串(可能是一句话)中最长的单词并且将其长度输出。主要使用了for、sort()和reduce()方法,当然在具体实现功能过程中,还运用到了JavaScript中的split()、pop()和Math.max()等方法。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,264评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,549评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,389评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,616评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,461评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,351评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,776评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,414评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,722评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,760评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,537评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,381评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,787评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,030评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,304评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,734评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,943评论 2 336

推荐阅读更多精彩内容