【Codewars】<6kyu>Calculate String Rotation

一、题目:

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.


For instance, take the strings “fatigue” and “tiguefa”. In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned.


If the second string isn’t a valid rotation of the first string, the method returns -1.
这道题要我们编写一个接收两个字符串并返回n的函数,其中n等于我们应该将第一个字符串前移(右移)以匹配第二个字符串的字符数。
如果第二个字符串不是第一个字符串前移(右移)可以得到,则该方法返回-1。

二、例子:

"coffee", "eecoff" => 2
"eecoff", "coffee" => 4
"moose", "Moose" => -1
"isn't", "'tisn" => 2
"Esham", "Esham" => 0
"dog", "god" => -1

三、题解一:

function shiftedDiff(first,second){
    for(let i=0;i<first.length;i++){
        if(first.substr(first.length-i,i) + first.substr(0, first.length-i) == second) return i;
    }
    return -1;
}

四、题解二:(Best Practices)

function shiftedDiff(first, second) {
  if (first.length != second.length) return -1
  return (second + second).indexOf(first)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值