问题
On Hackerrank I came across this problem. I have a function that takes in 3 arguments. Example --> function shiftStrings("string", leftShifts, rightShifts); LeftShifts and rightShifts being integers.
Left Shift: A single circular rotation of the string in which the first character becomes the last character and all other characters are shifted one index to the left. For example, abcde becomes bcdea after one left shift and cdeab after two left shifts.
Right Shift: A single circular rotation of the string in which the last character becomes the first character and all other characters are shifted to the right. For example, abcde becomes eabcd after one right shift and deabc after two right shifts.
I passed 7 out of 13 test cases, but the other five were timed out. Here is my solution
function getShiftedString(s, leftShifts, rightShifts) {
// Write your code here
let arr = s.split('');
for (let i = 0; i < leftShifts; i++) {
let arrItem = arr[0];
arr.shift();
arr.push(arrItem);
};
for (let i = 0; i < rightShifts; i++) {
let arrItem = arr[arr.length - 1];
arr.pop();
arr.unshift(arrItem);
};
const finished = arr.join('');
return finished;
}
Any ideas on a better way to do this? I'm newer to programming and trying to get algorithm practice in.
回答1:
It would probably be easier to use slice (which can accept negative indicies), and calculate the net shift initially, so that only one actual shifting operation needs to occur:
function getShiftedString(s, leftShifts, rightShifts) {
// using `split('')` will result in certain unicode characters being separated incorrectly
// use Array.from instead:
const arr = Array.from(s);
const netLeftShifts = (leftShifts - rightShifts) % arr.length;
return [...arr.slice(netLeftShifts), ...arr.slice(0, netLeftShifts)]
.join('');
}
console.log([
getShiftedString('abc', 0, 0),
getShiftedString('abc', 1, 0),
getShiftedString('abc', 0, 1),
getShiftedString('abc', 1, 1),
getShiftedString('123456789', 0, 0),
getShiftedString('123456789', 1, 5),
getShiftedString('123456789', 5, 1),
'----',
getShiftedString('123456789', 9, 0),
getShiftedString('123456789', 10, 0),
getShiftedString('123456789', 0, 9),
getShiftedString('123456789', 0, 10),
getShiftedString("🐎👱❤", 0, 0),
getShiftedString("🐎👱❤", 1, 0),
]);
回答2:
Here is my solution for left shift and right shift using splice and spread operator.
//left
let str="abcde";
let arr=Array.from(str);
let left_shift=2;
let x=arr.splice(0, left_shift);
console.log([...arr,x].flat().join(""));
//right
let arr1=Array.from(str).reverse();
let right_shift=2;
let x1=arr1.splice(0, right_shift);
console.log([...arr1,x1].flat().reverse().join(""));
来源:https://stackoverflow.com/questions/55152391/shift-strings-circular-left-and-right