We define the following operations on a string:
- 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 one index
to the right. For example, abcde becomes eabcd after
one right shift and deabc after two right shifts.
Function Description
Complete the function getShiftedString in the
editor below. The function must return the string s after
performing the stated shifts.
getShiftedString has the following parameter(s):
s: the string to shift
leftShifts: integer
rightShifts: integer
Constraints
- 1 ≤ |s| ≤ 105
- 0 ≤ leftShifts, rightShifts ≤ 109
- String s consists of lowercase English alphabetic letters only, ascii[a-z].
- Input Format for Custom Testing.
- Input from stdin will be processed as follows and passed to the function.
- The first line contains s, the string to shift.
- The second line contains an integer, leftShifts.
- The third line contains an integer, rightShifts.
getShiftedString <- function(s, leftShifts, rightShifts) {
# Write your code here
if( leftShifts == 0 & rightShifts == 0 ){
paste0(s)
}
else if(leftShifts == 0)
{
paste0(substr(s,nchar(s)-rightShifts+1,nchar(s)), substr(s,1,nchar(s)-rightShifts))
}
else if(rightShifts == 0)
{
paste0(substr(s,leftShifts,nchar(s)),substr(s,0,leftShifts-1))
}
else if(rightShifts == leftShifts)
{
paste0(s)
}
else{
if( leftShifts > nchar(s) & rightShifts > nchar(s)){
while (leftShifts > nchar(s)) {
leftShifts <- leftShifts - nchar(s)
}
while (rightShifts > nchar(s)) {
rightShifts <- rightShifts - nchar(s)
}
}
s <- paste0(substr(s,leftShifts+1,nchar(s)),substr(s,0,leftShifts))
paste0(substr(s,nchar(s)-rightShifts+1,nchar(s)), substr(s,1,nchar(s)-rightShifts))
}
}
getShiftedString <- function(s, leftShifts, rightShifts) {
# Write your code here
if( leftShifts == 0 & rightShifts == 0 ){
paste0(s)
}
else if(leftShifts == 0)
{
paste0(substr(s,nchar(s)-rightShifts+1,nchar(s)), substr(s,1,nchar(s)-rightShifts))
}
else if(rightShifts == 0)
{
paste0(substr(s,leftShifts,nchar(s)),substr(s,0,leftShifts-1))
}
else if(rightShifts == leftShifts)
{
paste0(s)
}
else{
if( leftShifts > nchar(s) & rightShifts > nchar(s)){
while (leftShifts > nchar(s)) {
leftShifts <- leftShifts - nchar(s)
}
while (rightShifts > nchar(s)) {
rightShifts <- rightShifts - nchar(s)
}
}
s <- paste0(substr(s,leftShifts+1,nchar(s)),substr(s,0,leftShifts))
paste0(substr(s,nchar(s)-rightShifts+1,nchar(s)), substr(s,1,nchar(s)-rightShifts))
}
}
No comments:
Post a Comment