题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
思路: 这题乍一看挺简单,但需要注意左移的位数可能会大于字符串的长度,故要记得先取模。
class Solution {
public:
string LeftRotateString(string str, int n) {
int len = str.size();
if (len == 0) return "";
if (n == len || n == 0) return str;
string s;
n = n % len; //考虑n大于len的情况,需要取模
for (int i = n; i < len; i++)
s.push_back(str[i]);
for (int i = 0; i < n; i++)
s.push_back(str[i]);
return s;
}
};
Python
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
if len(s) == 0:
return ''
if n == len or n == 0: #or不要写成c++的||了
return s
n = n % len(s)
return s[n:] + s[:n]