58-II. 左旋转字符串
1. 描述
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
2. 例子
示例 1:
输入: s = “abcdefg”, k = 2
输出: “cdefgab”
示例 2:
输入: s = “lrloseumgh”, k = 6
输出: “umghlrlose”
3. 限制
- 1 <= k < s.length <= 10000
4. 题解
n = m_sentence.size()
时间复杂度: O(n)
空间复杂度: O(1)
class Solution
{
public:
// string reverseLeftWords(string s, int n)
string reverseLeftWords(string &m_sentence, int k)
{
reverse(m_sentence.begin(), m_sentence.end());
reverse(m_sentence.begin(), m_sentence.begin() + m_sentence.size() - k);
reverse(m_sentence.begin() + m_sentence.size() - k, m_sentence.end());
return m_sentence;
}
};