Skip to content

Commit 6e41594

Browse files
committed
feat: add rotate string left at position k.
1 parent 221e281 commit 6e41594

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

leetcode/string/rotate_string_left

58.1 KB
Binary file not shown.
+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-03-20 13:26:59
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-03-20 13:54:43
6+
*/
7+
8+
/**
9+
* 来源:https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/
10+
*
11+
* 剑指 Offer 58 - II.左旋转字符串
12+
* 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。
13+
* 比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
14+
*
15+
* 1 <= k < s.length <= 10000
16+
*
17+
* 示例 1:
18+
* 输入: s = "abcdefg", k = 2
19+
* 输出: "cdefgab"
20+
*
21+
* 示例 2:
22+
* 输入: s = "lrloseumgh", k = 6
23+
* 输出: "umghlrlose"
24+
*
25+
*/
26+
#include <string>
27+
#include <iostream>
28+
29+
using namespace std;
30+
31+
class Solution
32+
{
33+
private:
34+
/* data */
35+
public:
36+
string reverseStringLeft(string s, int n);
37+
};
38+
39+
/**
40+
*
41+
* 可以通过 局部反转+整体反转 达到左旋转的目的。具体步骤为:
42+
* 1. 反转区间为前 k 的子串
43+
* 2. 反转区间为 k 到末尾的子串
44+
* 3. 反转整个字符串
45+
*
46+
* 最后就可以得到左旋n的目的,而不用定义新的字符串,完全在本串上操作。
47+
*
48+
* 示例 1:
49+
*
50+
* 字符串: a b | c d e f g
51+
* 反转 0 到 k-1: b a | c d e f g
52+
* 反转 k 到 len-1: b a | g f e d c
53+
* 反转整个字符串: c d e f g a b
54+
*
55+
* 最后得到 cdefgab
56+
*
57+
*/
58+
string Solution::reverseStringLeft(string s, int k)
59+
{
60+
reverse(s.begin(), s.begin() + k);
61+
reverse(s.begin() + k, s.end());
62+
reverse(s.begin(), s.end());
63+
return s;
64+
}
65+
66+
int main(int argc, char const *argv[])
67+
{
68+
Solution s;
69+
70+
string str1 = "abcdefg";
71+
string str2 = "lrloseumgh";
72+
73+
cout << "abcdefg 在 k = 2 反转后:" << s.reverseStringLeft(str1, 2) << endl; // cdefgab
74+
cout << "lrloseumgh 在 k = 6 反转后:" << s.reverseStringLeft(str2, 6) << endl; // umghlrlose
75+
76+
return 0;
77+
}

0 commit comments

Comments
 (0)