> For the complete documentation index, see [llms.txt](https://zhongquan789.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zhongquan789.gitbook.io/leetcode/lcof/mian-shi-ti-58-ii.md).

# 面试题58 - II

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如，输入字符串"abcdefg"和数字2，该函数将返回左旋转两位得到的结果"cdefgab"。

```
示例 1：

输入: s = "abcdefg", k = 2
输出: "cdefgab"

示例 2：

输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"
```

## 限制：

* 1 <= k < s.length <= 10000

## Solutions

* The same as `problem 189`.
* **reverse**

```cpp
class Solution {
public:
    string reverseLeftWords(string s, int n) {
        n %= s.size(); if (!n) return s;
        reverse(s.begin(), s.end());
        reverse(s.begin(), s.begin() + n);
        reverse(s.begin() + n, s.end());

        return s;
    }
};
```

1. **cycle placement**

```cpp
class Solution {
public:
    string reverseLeftWords(string s, int n) {
        n =  s.size() - (n % s.size()); if (!n) return s;

        for (int i = 0, times = 0; times < s.size(); i++) {
            int curi = i;
            do {
                int nexti = (curi + n) % s.size();
                swap(s[i], s[nexti]);
                curi = nexti;
                times++;
            } while (curi != i);
        }

        return s;
    }
};
```
