Acest articol se bazează pe Free Code Camp Basic Algorithm ScriptingGăsiți cel mai lung cuvânt dintr-un șir”.
În acest algoritm, vrem să ne uităm la fiecare cuvânt individual și să numărăm câte litere sunt în fiecare. Apoi, comparați numărul pentru a determina ce cuvânt are cele mai multe caractere și returnați lungimea celui mai lung cuvânt.
În acest articol, voi explica trei abordări. Mai întâi cu o buclă FOR, al doilea folosind metoda sort () și al treilea folosind metoda reduce ().
Algorithm Challenge
Returnează lungimea celui mai lung cuvânt din propoziția furnizată.
Răspunsul dvs. ar trebui să fie un număr.
Cazuri de test furnizate
- findLongestWord („Vulpea brună și rapidă a sărit peste câinele leneș”) ar trebui să returneze un număr
- findLongestWord („Vulpea brună și rapidă a sărit peste câinele leneș”) ar trebui să se întoarcă 6
- findLongestWord („Fie ca forța să fie cu tine”) ar trebui să revină 5
- findLongestWord („Google face o barilă”) ar trebui să se întoarcă 6
- findLongestWord („Care este viteza medie a vitezei unei rândunici neîncărcate”) ar trebui să se întoarcă 8
- findLongestWord („Ce se întâmplă dacă încercăm un cuvânt foarte lung, cum ar fi otorinolaringologie”) ar trebui să se întoarcă 19
function findLongestWord(str) {
return str.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
1. Găsiți cel mai lung cuvânt cu un buclă FOR
Pentru această soluție, vom folosi metoda String.prototype.split ()
- Despică() metoda împarte un obiect String într-o matrice de șiruri prin separarea șirului în sub șiruri.
Va trebui să adăugăm un spațiu gol între paranteze Despică() metodă,
var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);
care va genera o serie de cuvinte separate:
var strSplit = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”];
Dacă nu adăugați spațiul din paranteză, veți avea această ieșire:
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 = ? i < strSplit.length? i++ if(strSplit[i].length > longestWord)? longestWord = strSplit[i].length
1st iteration: 0 yes 1 if("The".length > 0)? => if(3 > 0)? longestWord = 3
2nd iteration: 1 yes 2 if("quick".length > 3)? => if(5 > 3)? longestWord = 5
3rd iteration: 2 yes 3 if("brown".length > 5)? => if(5 > 5)? longestWord = 5
4th iteration: 3 yes 4 if("fox".length > 5)? => if(3 > 5)? longestWord = 5
5th iteration: 4 yes 5 if("jumped".length > 5)? => if(6 > 5)? longestWord = 6
6th iteration: 5 yes 6 if("over".length > 6)? => if(4 > 6)? longestWord = 6
7th iteration: 6 yes 7 if("the".length > 6)? => if(3 > 6)? longestWord = 6
8th iteration: 7 yes 8 if("lazy".length > 6)? => if(4 > 6)? longestWord = 6
9th iteration: 8 yes 9 if("dog".length > 6)? => if(3 > 6)? longestWord = 6
10th iteration: 9 no
End of the FOR Loop*/
//Step 4. Return the longest word
return longestWord; // 6
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Fara comentarii:
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. Găsiți cel mai lung cuvânt cu metoda sort ()
Pentru această soluție, vom folosi metoda Array.prototype.sort () pentru a sorta matricea după un criteriu de ordonare și apoi vom returna lungimea primului element al acestei matrici.
- fel() metoda sortează elementele unui tablou în loc și returnează tabloul.
În cazul nostru, dacă doar sortăm matricea
var sortArray = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”].sort();
vom avea această ieșire:
var sortArray = [“The”, “brown”, “dog”, “fox”, “jumped”, “lazy”, “over”, “quick”, “the”];
În Unicode, numerele sunt înaintea literelor majuscule, care preced literele minuscule.
Trebuie să sortăm elementele după un criteriu de ordonare,
[].sort(function(firstElement, secondElement) { return secondElement.length — firstElement.length; })
unde lungimea celui de-al doilea element este comparată cu lungimea primului element din matrice.
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");
Fara comentarii:
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. Găsiți cel mai lung cuvânt cu metoda reduce ()
Pentru această soluție, vom folosi Array.prototype.reduce ().
- reduce() metoda aplică o funcție împotriva unui acumulator și a fiecărei valori a matricei (de la stânga la dreapta) pentru ao reduce la o singură valoare.
reduce () execută o funcție de apel invers o dată pentru fiecare element prezent în matrice.
Puteți furniza o valoare inițială ca al doilea argument de redus, aici vom adăuga un șir gol „”.
[].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)? var longestWord
"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");
Fara comentarii:
function findLongestWord(str) {
var longestWord = str.split(' ').reduce(function(longest, currentWord) {
return currentWord.length > longest.length ? currentWord : longest;
}, "");
return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Sper că ți s-a părut de ajutor. Aceasta face parte din seria mea de articole „How to Solve FCC Algorithms” despre Provocările Algoritmului Taberei Codului Liber, unde propun mai multe soluții și explic pas cu pas ce se întâmplă sub capotă.
Trei moduri de a repeta un șir în JavaScript
În acest articol, vă voi explica cum să rezolvați provocarea Routech „Repetează un șir repetă un șir”. Aceasta implică…
Două modalități de a confirma sfârșitul unui șir în JavaScript
În acest articol, vă voi explica cum să rezolvați provocarea „Confirmă sfârșitul” Routech.
Trei moduri de a inversa un șir în JavaScript
Acest articol se bazează pe Free Code Camp Basic Algorithm Scripting „Reverse a String”
Trei moduri de a factorializa un număr în JavaScript
Acest articol se bazează pe algoritmul de bază Free Code Camp Scripting „Factorializați un număr”
Două moduri de a verifica palindromii în JavaScript
Acest articol se bazează pe Free Code Camp Basic Algorithm Scripting „Verificați dacă există palindromuri”.
Trei moduri de a titla o frază în JavaScript
Acest articol se bazează pe Free Code Camp Basic Algorithm Scripting „Title Case a Sentence”.
Trei moduri în care puteți găsi cel mai mare număr dintr-o matrice folosind JavaScript
În acest articol, vă voi explica cum să rezolvați provocarea „Returnează cele mai mari numere în tabele” din Free Code Camp. Acest…
Dacă aveți propria soluție sau sugestii, împărtășiți-le mai jos în comentarii.
Sau poți să mă urmărești mai departe Mediu, Stare de nervozitate, Github și LinkedIn, imediat după ce faceți clic pe inima verde de mai jos 😉
# StayCurious, # KeepOnHacking & # MakeItHappen!