-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path1790.rotate-string-ii.cpp
50 lines (47 loc) · 1.79 KB
/
1790.rotate-string-ii.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Tag: String
// Time: O(N)
// Space: O(N)
// Ref: -
// Note: Simulation
// Given a string(Given in the way of char array), a right offset and a left offset, move the string cyclically according to the given offset and save it in a new result set for return.
// (Left offest represents the offset of a string to the left,right offest represents the offset of a string to the right,the total offset is calculated from the left offset and the right offset, split two strings at the total offset and swap positions.)
//
// **Example 1:**
// ```
// Input:str ="abcdefg", left = 3, right = 1
// Output:"cdefgab"
// Explanation:The left offset is 3, the right offset is 1, and the total offset is left 2. Therefore, the original string moves to the left and becomes "cdefg"+ "ab".
// ```
//
// **Example 2:**
// ```
// Input:str="abcdefg", left = 0, right = 0
// Output:"abcdefg"
// Explanation:The left offset is 0, the right offset is 0, and the total offset is 0. So the string remains unchanged.
// ```
//
//
// **Example 3:**
// ```
// Input:str = "abcdefg",left = 1, right = 2
// Output:"gabcdef"
// Explanation:The left offset is 1, the right offset is 2, and the total offset is right 1. Therefore, the original string moves to the left and becomes "g" + "abcdef".
// ```
//
//
class Solution {
public:
/**
* @param str: An array of char
* @param left: a left offset
* @param right: a right offset
* @return: return a rotate string
*/
string rotateString2(string &str, int left, int right) {
// write your code here
int length = str.size();
int pos = (left - right) % length;
pos = pos > 0 ? pos : length + pos;
return str.substr(pos, length - pos) + str.substr(0, pos); // pos, length
}
};