You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]:
directioncan be0(for left shift) or1(for right shift).amountis the amount by which stringsis to be shifted.- A left shift by 1 means remove the first character of
sand append it to the end. - Similarly, a right shift by 1 means remove the last character of
sand add it to the beginning.
Return the final string after all operations.
Example 1:
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:
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”
Constraints:
1 <= s.length <= 100sonly contains lower case English letters.1 <= shift.length <= 100shift[i].length == 20 <= shift[i][0] <= 10 <= shift[i][1] <= 100
求解
class Solution {public String stringShift(String s, int[][] shift) {int headIndex = 0;int shiftCount = 0;for (int i = 0; i < shift.length ; i++) {if (shift[i][0] == 0){shiftCount += shift[i][1]; //headIndex + 1}else {shiftCount -= shift[i][1];}}char[] arr = s.toCharArray();headIndex = (headIndex+shiftCount + arr.length * 100) % arr.length;StringBuilder res = new StringBuilder();for (int i = headIndex; i < arr.length; i++) {res.append(arr[i]);}for (int i = 0; i < headIndex; i++) {res.append(arr[i]);}return res.toString();}public static void main(String[] args) {// "cab"// System.out.println((new Solution()).stringShift(new String("abc"), new int[][]{{0,1},{1,2}}));// "efgabcd"// System.out.println((new Solution()).stringShift(new String("abcdefg"), new int[][]{{1,1},{1,1},{0,2},{1,3}}));System.out.println((new Solution()).stringShift(new String("yzeuobhwxatulpruiab"), new int[][]{{1,15},{0,18},{0,12},{0,7},{0,7},{1,17},{1,15},{0,9},{1,4},{0,19},{1,16},{0,7},{1,4},{1,17},{1,19},{1,10},{1,2},{0,18},{1,15}}));}}
