题目分析:[[EVD]] - 剑指 Offer 58 - II. 左旋转字符串
https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/
简单描述:
- 实现字符串左旋转操作的功能
限制🚫
- 1 <= k < s.length <= 10000
示例:
输入: s = "abcdefg", k = 2
输出: "cdefgab"
解题思路:
思路:
- 1.旧字符串分割后拼接成新字符串
- 遍历拼接
- 利用string库函数substr分割 #[[C++ STL]]
- 2.添加到尾部,然后进行截断
- 利用string库函数resize分割 #[[C++ STL]]
- 利用string库函数erase分割 #[[C++ STL]]
- 3.3次反转
- 利用algorithm库中函数reverse(底层实现为元素交换) #[[C++ STL]]
效率:
- 1.拼接 2.截断 时间复杂度
,空间复杂度
- 3.反转 时间复杂度
,空间复杂度
代码:
- 1.拼接
class Solution
{
public:
string reverseLeftWords(string s, int n)
{
return s.substr(n) + s.substr(0, n);
}
};
- 2.截断
class Solution
{
public:
/*添加到尾部,然后截断*/
string reverseLeftWords(string s, int n)
{
for (int i = 0; i < n; i++)
s.push_back(s[i]);
s.erase(0, n);
return s;
}
};
- 3.反转
class Solution
{
public:
/*反转*/
string reverseLeftWords(string s, int n)
{
reverse(s.begin(), s.begin() + n);
reverse(s.begin() + n, s.end());
reverse(s.begin(), s.end());
return s;
}
};