【问题标题】:JavaScript function receives two strings and returns nJavaScript 函数接收两个字符串并返回 n
【发布时间】:2019-10-26 12:44:40
【问题描述】:
我最近一直在尝试完成这个挑战但没有成功,尝试了很多方法但是
由于某种原因,我无法完成以下所有示例。
如果有人可以帮助我,一步一步地告诉我,我将不胜感激。
编写一个接收两个字符串并返回n的函数,其中n为
等于我们应该移动第一个字符串的字符数
前进以匹配第二个。例如,使用字符串“fatigue”
和“tiguefa”。在这种情况下,第一个字符串已旋转 5
字符向前产生第二个字符串,所以 5 将是
返回。
如果第二个字符串不是第一个字符串的有效旋转,则
方法返回 -1。规范 shiftDiff(first, second) 提供
匹配单词的旋转量
参数第一:字符串-要匹配的单词
second: String - 要检查的单词
返回值 Number - 旋转次数,nil 或 -1 如果无效
例子:
- "coffee", "eecoff" => 2
- "eecoff", "coffee" => 4
- “驼鹿”,“驼鹿” => -1
- "不是", "'tisn" => 2
- "Esham", "Esham" => 0
- “狗”,“神” => -1
【问题讨论】:
标签:
javascript
substring
logic
【解决方案1】:
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
文档
【解决方案2】:
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"))