1.题目引入:
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
请定义一个函数实现字符串左旋转操作的功能。
比如输入字符串
"abcdefg"
和数字 22,该函数将返回左旋转 22 位得到的结果"cdefgab"
。注意:
- 数据保证 nn 小于等于输入字符串的长度。
数据范围
输入字符串长度 [0,1000][0,1000]。
2.样例输出:
样例
输入:"abcdefg" , n=2 输出:"cdefgab"
3.代码如下:
利用 STL容器:
class Solution {
public:
string leftRotateString(string str, int n) {
return str.substr(n)+str.substr(0,n);
}
};
直接利用 string 的字符串特性:
class Solution { public: string leftRotateString(string str, int n) { string s1(str.begin() + n, str.end()); string s2 (str.begin(), str.begin() + n); return s1 + s2; } };
python 做法:
class Solution(object):
def leftRotateString(self, s, n):
"""
:type s: str
:type n: int
:rtype: str
"""
return s[n:] + s[:n]