problem
You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]:
direction can be 0 (for left shift) or 1 (for right shift).
amount 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.
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”
solution
1×1+1×1+(-1)×2+1×3=3,意思就是向右移三个,和最后一个刚好匹配,就是前面的通过抵消计算就会“平衡”
特例:注意一个的情况,直接返回
看到这个题目,移动,就感觉和一个数组反转题目很相似,可以用同样的方法,快速反转吧
python
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
if len(s)<2:
return s
//length=len(shift)
length=len(s)
sum=0
for i in shift:
sum=sum+(i[1] if i[0]==1 else -i[1])
if sum==0:
return s
if sum>0:
sum=sum % length
return s[length-sum:length]+s[:length-sum]
# 忘记给负数取绝对值
# return s[sum:length]+s[0:sum]
# 完全没有考虑到数组边界问题,还要记得取余
# return s[sum:length]+s[0:sum]
sum=abs(sum) % length
return s[sum:length]+s[0:sum]
java
class Solution {
public String stringShift(String s, int[][] shift) {
int length = s.length();
int lengthshift=shift.length;
if (length<2){
return s;
}
int sum=0;
for(int i=0;i<lengthshift;++i){
sum=sum+ (shift[i][0]==1?shift[i][1]:-shift[i][1]);
// 这里开始没有加1括号,结果运算的时候就先算前面的加法,后面再运算三目运算符
// sum=sum+ shift[i][0]==1?shift[i][1]:-shift[i][1];
}
if(sum==0){
return s;
}
else if(sum>0){
sum=sum % length;
return s.substring(length-sum,length)+s.substring(0,length-sum);
}
else{
sum=Math.abs(sum) % length;
return s.substring(sum,length)+s.substring(0,sum);
}
}
}