本文基于Free Code Camp基本算法脚本“查找字符串中最长的单词”。

在此算法中,我们要查看每个单词并计算每个单词中有多少个字母。然后,比较计数以确定哪个单词的字符最多,并返回最长单词的长度。

在本文中,我将解释三种方法。首先使用FOR循环,其次使用sort()方法,第三次使用reduce()方法。

算法挑战

  • 返回提供的句子中最长单词的长度。
  • 您的回复应该是一个数字。

提供的测试用例

  • findLongestWord(“The quick brown fox jumped over the lazy dog”)返回一个数字
  • 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
function findLongestWord(str) {
 return str.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

1.使用FOR循环查找最长的单词

对于此解决方案,我们将使用String.prototype.split()方法

  • split()的方法通过分离串分成子串分割字符串对象到字符串数组。

我们将需要在split()方法的括号之间添加一个空格

var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);

它将输出一个由单词组成的数组:

var strSplit = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”];

如果不在括号中添加空格,则将得到以下输出:

var strSplit = 
[“T”, “h”, “e”, “ “, “q”, “u”, “i”, “c”, “k”, “ “, “b”, “r”, “o”, “w”, “n”, “ “, “f”, “o”, “x”, “ “, “j”, “u”, “m”, “p”, “e”, “d”, “ “, “o”, “v”, “e”, “r”, “ “, “t”, “h”, “e”, “ “, “l”, “a”, “z”, “y”, “ “, “d”, “o”, “g”];
function findLongestWord(str) {
 // Step 1. Split the string into an array of strings
 var strSplit = str.split(' ');
 // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
 // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
 
 // Step 2. Initiate a variable that will hold the length of the longest word
 var longestWord = 0;

 // Step 3. Create the FOR loop
 for(var i = 0; i < strSplit.length; i++){
 if(strSplit[i].length > longestWord){ // If strSplit[i].length is greater than the word it is compared with...
 longestWord = strSplit[i].length; // ...then longestWord takes this new value
  }
 }
 /* Here strSplit.length = 9
  For each iteration: i = "The".length > 0)"quick".length > 3)"brown".length > 5)"fox".length > 5)"jumped".length > 5)"over".length > 6)"the".length > 6)"lazy".length > 6)"dog".length > 6)"The quick brown fox jumped over the lazy dog");

没有注释:

function findLongestWord(str) {
 var strSplit = str.split(' ');
 var longestWord = 0;
 for(var i = 0; i < strSplit.length; i++){
 if(strSplit[i].length > longestWord){
 longestWord = strSplit[i].length;
  }
 }
 return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

2.使用sort()方法找到最长的单词

对于此解决方案,我们将使用Array.prototype.sort()方法按照某种排序标准对数组进行排序,然后返回此数组的第一个元素的长度。

  • sort()的方法进行排序的阵列的代替元素并返回数组。

就我们而言,如果我们只是对数组排序

var sortArray = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”].sort();

我们将得到以下输出:

var sortArray = [“The”, “brown”, “dog”, “fox”, “jumped”, “lazy”, “over”, “quick”, “the”];

在Unicode中,数字在大写字母之前,而在小写字母之前。

我们需要按照某种排序标准对元素进行排序

[].sort(function(firstElement, secondElement) {  return secondElement.length — firstElement.length; })

比较第二个元素的长度和数组中第一个元素的长度。

function findLongestWord(str) {
 // Step 1. Split the string into an array of strings
 var strSplit = str.split(' ');
 // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
 // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
 
 // Step 2. Sort the elements in the array
 var longestWord = strSplit.sort(function(a, b) { 
 return b.length - a.length;
 });
 /* Sorting process
 a   b   b.length  a.length  var longestWord
 "The"  "quick"   5   3   ["quick", "The"]
 "quick" "brown"   5   5   ["quick", "brown", "The"] 
 "brown" "fox"    3   5   ["quick", "brown", "The", "fox"]
 "fox"  "jumped"   6   3   ["jumped", quick", "brown", "The", "fox"]
 "jumped" "over"    4   6   ["jumped", quick", "brown", "over", "The", "fox"]
 "over"  "the"    3   4   ["jumped", quick", "brown", "over", "The", "fox", "the"]
 "the"  "lazy"    4   3   ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the"]
 "lazy"  "dog"    3   4   ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the", "dog"]
 */
 
 // Step 3. Return the length of the first element of the array
 return longestWord[0].length; // var longestWord = ["jumped", "quick", "brown", "over", "lazy", "The", "fox", "the", "dog"];
        // longestWord[0]="jumped" => jumped".length => 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");

没有注释:

function findLongestWord(str) {
 var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
 return longestWord[0].length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

3.使用reduce()方法找到最长的单词

对于此解决方案,我们将使用Array.prototype.reduce()。

  • reduce()的方法应用于对一个储液器的功能和所述阵列的每一值(从左到右),以将其降低到一个值。

reduce()对数组中存在的每个元素执行一次回调函数。

您可以提供一个初始值作为要减少的第二个参数,这里我们将添加一个空字符串“”。

[].reduce(function(previousValue, currentValue) {...}, “”);
function findLongestWord(str) {
 // Step 1. Split the string into an array of strings
 var strSplit = str.split(' ');
 // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
 // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];

 // Step 2. Use the reduce method
 var longestWord = strSplit.reduce(function(longest, currentWord) {
 if(currentWord.length > longest.length)
  return currentWord;
 else
  return longest;
 }, "");
 
 /* Reduce process
 currentWord  longest  currentWord.length  longest.length if(currentWord.length > longest.length)"The"    ""     3      0        yes       "The"
 "quick"   "The"    5      3        yes       "quick"
 "brown"   "quick"    5      5        no       "quick"
 "fox"    "quick"    3      5        no       "quick"
 "jumped"   "quick"    6      5        yes       "jumped"
 "over"   "jumped"   4      6        no       "jumped"
 "the"    "jumped"   3      6        no       "jumped"
 "lazy"   "jumped"   4      6        no       "jumped"
 "dog"    "jumped"   3      6        no       "jumped"
 */
 
 // Step 3. Return the length of the longestWord
 return longestWord.length; // var longestWord = "jumped" 
        // longestWord.length => "jumped".length => 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");

没有注释:

function findLongestWord(str) {
 var longestWord = str.split(' ').reduce(function(longest, currentWord) {
 return currentWord.length > longest.length "");
 return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
标签:
js查找字符串最长单词,js查找字符串

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。