You are given a string
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.
Example 1:
Example 2:
Constraints:
1 <= s.length <= 100 s only contains lower case English letters.1 <= shift.length <= 100 shift[i].length == 2 0 <= shift[i][0] <= 1 0 <= shift[i][1] <= 100
Solution
As we know that one left shift and right shift will cancel each other, We can take advantage of it and count number of left and right shifts. Just shift Characters only difference of
Code
0 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 |
class Solution { public String stringShift(String s, int[][] shift) { if (s.length()<2) return s; int rCnt = 0, lCnt = 0; for (int[] sArr : shift) { if (sArr[0] == 0) lCnt += sArr[1]; else rCnt += sArr[1]; } if (rCnt == lCnt) return s; if (rCnt > lCnt) { rCnt = rCnt - lCnt; rCnt = rCnt % s.length(); return s.substring(s.length()-rCnt) + s.substring(0, s.length()-rCnt); } else { lCnt = lCnt - rCnt; lCnt = lCnt % s.length(); return s.substring(lCnt) + s.substring(0,lCnt); } } } |
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.