[英]JavaScript function receives two strings and returns n
I've been trying to complete this challenge recently but with no success, tried many ways but for some reason I don't manage to complete all the examples below.我最近一直在尝试完成这个挑战,但没有成功,尝试了很多方法,但由于某种原因,我无法完成下面的所有示例。
I will be appreciated if someone can assist me with that, showing me step by step.如果有人可以帮助我,我将不胜感激,一步一步地向我展示。
Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second.编写一个 function 接收两个字符串并返回 n,其中 n 等于我们应该将第一个字符串向前移动以匹配第二个字符串的字符数。 For instance, take the strings "fatigue" and "tiguefa".例如,使用字符串“fatigue”和“tiguefa”。 In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned.在这种情况下,第一个字符串向前旋转了 5 个字符以生成第二个字符串,因此将返回 5。
If the second string isn't a valid rotation of the first string, the method returns -1.如果第二个字符串不是第一个字符串的有效旋转,则该方法返回 -1。 Specification shiftedDiff(first, second) provide amount of rotations to match words规范 shiftDiff(first, second) 提供旋转量以匹配单词
Parameters first: String - word to be matched参数第一:字符串——要匹配的单词
second: String - word to be checked第二:字符串 - 要检查的单词
Return Value Number - Number of rotations, nil or -1 if invalid返回值 Number - 旋转次数,nil 或 -1 如果无效
Examples:例子:
function shiftedDiff(first, second) { // Split the second word into an array for // easier manipulation const arr = [...second]; // Iterate over the array for (let i = 0; i < arr.length; i++) { // If the first and joined array match // return the index if (first === arr.join('')) return i; // Otherwise `shift` off the first element of `arr` // and `push` it on the end of the array arr.push(arr.shift()); } // If there are no matches return -1 return -1; } console.log(shiftedDiff('coffee', 'eecoff')); // 2 console.log(shiftedDiff('eecoff', 'coffee')); // 4 console.log(shiftedDiff('moose', 'Moose')); // -1 console.log(shiftedDiff("isn't", "'tisn")); // 2 console.log(shiftedDiff('Esham', 'Esham')); // 0 console.log(shiftedDiff('dog', 'god')); // -1
let shiftedDiff = (f, s) => { let r = -1; f.split('').forEach((e, i) => { f = f.substr(1) + e; if (f == s) r = f.length - (i + 1) }) return r; } console.log(shiftedDiff("coffee", "eecoff")) console.log(shiftedDiff("eecoff", "coffee")) console.log(shiftedDiff("moose", "Moose")) console.log(shiftedDiff("isn't", "'tisn")) console.log(shiftedDiff("Esham", "Esham")) console.log(shiftedDiff("dog", "god"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.