问题描述
我对编程非常陌生,在寻求帮助时有点害羞......老实说,我被其他人解决问题的速度吓到了,所以对于那些属于这一类的人,我希望你能帮我解决一个家庭作业问题。 我不知道从哪里开始或编写伪代码,但如果你能指导我或给我一个详细的原因和方式的回复,我欠你一大笔债。 这是问题所在:
我们在字符串上定义以下操作:
左移:字符串的单个循环旋转,其中第一个字符成为最后一个字符,所有其他字符向左移动一个索引。 例如,bcdea 左移后变为 cdeab。
右移:同上,但反过来,最后一个字符成为第一个字符。
以下参数: s:字符串左移:整数右移:整数
约束:
1 <= 秒 <= 10^5
0 <= 左移,右移 <= 10^9
function getShiftedString(s, leftShifts, rightShifts) {
}
1楼
Ravi Teja
2
2019-11-26 13:23:42
function getShiftedString(s, leftShifts, rightShifts) {
s = leftShifting(s, leftShifts);
return rightShifting(s, rightShifts);
}
function leftShifting(s, leftShifts) {
return s.substring(leftShifts) + s.substring(0, leftShifts);
}
function rightShifting(s, rightShifts) {
let l = s.length - rightShifts;
return leftShifting(s, l);
}
尝试这个
2楼
Adam Lichter
1
2019-03-03 01:33:18
试着用伪代码写出来,这将帮助你规划你的功能。
想想你需要这个函数做什么,你需要它: 接受一个字符串 将它向右移动 x 次,将它向左移动 y 次
所以也许你的伪代码看起来有点像这样
s = string, x = left, y = right
convert s to array
for (x times)
q = first element in array
remove first element from array
add q to end of array
for (y times)
q = last element in array
remove last element from array
add q to the beginning of the array
make s string again
return s
那么这只是将其转换为代码的简单问题。
请记住,这只是一种解决方案,而且还有更好的解决方案。 一定要按照 Neil Lunn 所说的去做,并查看字符串转换。