# 面试题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;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zhongquan789.gitbook.io/leetcode/lcof/mian-shi-ti-58-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
