给定一个大小为n的字符串,编写函数对该字符串执行以下操作。
null
- 将给定字符串向左(或逆时针)旋转d个元素(其中d<=n)。
- 将给定的字符串向右(或顺时针)旋转d个元素(其中d<=n)。
例如:
Input : s = "GeeksforGeeks" d = 2 Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeeksforGee" Input : s = "qwertyu" d = 2 Output : Left rotation : "ertyuqw" Right rotation : "yuqwert"
我们有解决这个问题的现有方案,请参考 字符串的左旋转和右旋转 链接我们将使用python快速解决这个问题 线切割 .方法非常简单,
- 把绳子分成两部分 第一和第二 对于 左旋转 Lfirst=str[0:d]和Lsecond=str[d:]。对于 右旋 Rfirst=str[0:len(str)-d]和Rsecond=str[len(str)-d:]。
- 现在将这两部分连接起来 第二+第一 照着
# Function to rotate string left and right by d length def rotate( input ,d): # slice string in two parts for left and right Lfirst = input [ 0 : d] Lsecond = input [d :] Rfirst = input [ 0 : len ( input ) - d] Rsecond = input [ len ( input ) - d : ] # now concatenate two parts together print ( "Left Rotation : " , (Lsecond + Lfirst) ) print ( "Right Rotation : " , (Rsecond + Rfirst)) # Driver program if __name__ = = "__main__" : input = 'GeeksforGeeks' d = 2 rotate( input ,d) |
输出:
Left Rotation : eksforGeeksGe Right Rotation : ksGeeksforGee
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END