[LeetCode] Perform String Shifts

1427. Perform String Shifts

You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [directioni, amounti]:

  • directioni can be 0 (for left shift) or 1 (for right shift).
    amounti is the amount by which string s is to be shifted.
  • A left shift by 1 means remove the first character of s and append it to the end.
  • Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.

Return the final string after all operations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
string stringShift(string s, vector<vector<int>>& shift) {
int len = s.length(), mv = 0;
for(auto shi : shift) {
if(shi[0] == 0) mv -= shi[1];
else mv += shi[1];
}
mv %= len;
if(mv < 0) mv += len;

return s.substr(len-mv) + s.substr(0, len - mv);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/26/PS/LeetCode/perform-string-shifts/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.