Input: s ="abc", shift =[[0,1],[1,2]]Output: "cab"Explanation:
[0,1] means shift to left by 1."abc"->"bca"[1,2] means shift to right by 2."bca"->"cab"
Example 2:
1
2
3
4
5
6
7
Input: s ="abcdefg", shift =[[1,1],[1,1],[0,2],[1,3]]Output: "efgabcd"Explanation:
[1,1] means shift to right by 1."abcdefg"->"gabcdef"[1,1] means shift to right by 1."gabcdef"->"fgabcde"[0,2] means shift to left by 2."fgabcde"->"abcdefg"[1,3] means shift to right by 3."abcdefg"->"efgabcd"
Instead of performing each shift operation one by one, we can combine all shifts into a single net shift. Left and right shifts can be combined by adding/subtracting their amounts, and the result can be applied in one go.
classSolution {
public String stringShift(String s, int[][] shift) {
int n = s.length(), net = 0;
for (int[] op : shift) net += (op[0]== 1 ? op[1] : -op[1]);
net = ((net % n) + n) % n;
return s.substring(n - net) + s.substring(0, n - net);
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funstringShift(s: String, shift: Array<IntArray>): String {
val n = s.length
var net = 0for (op in shift) net +=if (op[0] ==1) op[1] else -op[1]
net = ((net % n) + n) % n
return s.substring(n - net) + s.substring(0, n - net)
}
}
1
2
3
4
5
6
defstringShift(s: str, shift: list[list[int]]) -> str:
n, net = len(s), 0for d, a in shift:
net += a if d ==1else-a
net = (net % n + n) % n
return s[-net:] + s[:-net] if net else s
1
2
3
4
5
6
7
8
9
10
11
12
13
fnstring_shift(s: &str, shift: Vec<Vec<i32>>) -> String {
let n = s.len();
letmut net =0;
for op in shift.iter() {
if op[0] ==1 { net += op[1]; } else { net -= op[1]; }
}
let net = ((net % n asi32) + n asi32) % n asi32;
let bytes = s.as_bytes();
letmut res = Vec::with_capacity(n);
res.extend_from_slice(&bytes[(n asi32- net) asusize..]);
res.extend_from_slice(&bytes[..(n asi32- net) asusize]);
String::from_utf8(res).unwrap()
}