Day 14 of 30-Day LeetCode Challenge
You are given a string s
containing lowercase English letters, and a matrix shift
, where shift[i] = [direction, amount]
:
direction
can be0
(for left shift) or1
(for right shift).amount
is the amount by which strings
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.
C++ Solution : O(n) time & O(1) space
static auto x = [](){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return nullptr;
}();
class Solution {
public:
string shiftByK(string s, int k){
reverse(s.begin(), s.begin()+k);
reverse(s.begin()+k, s.end());
reverse(s.begin(), s.end());
return s;
}
string stringShift(string s, vector<vector<int>>& shift) { //O(n) time & O(1) space
int shiftValue = 0;
//left shift : negative
//right shift : positive
for(int i=0;i<shift.size();++i){
if(shift[i][0]==0) shiftValue += (-1*shift[i][1]);
else if(shift[i][0]==1) shiftValue += shift[i][1];
}
int k = 0; //rotate string anti-clockwise k time
if(shiftValue<0){
//left shift by abs(shift)
if(abs(shiftValue)>s.size()) shiftValue = abs(shiftValue)%s.size();
k = abs(shiftValue);
}else if(shiftValue>0){
//right shift by abs(shift)
if(shiftValue>s.size()) shiftValue = shiftValue%s.size();
k = s.size()-shiftValue;
}
return shiftByK(s, k);
}
};