[LeetCode] Perform String Shifts

这题没有题号,是美版LC三十天挑战里面的一道题。题意是给一个string S和一个二维数组shift,请你根据shift里面的情况改动S,最后输出S被修改过后的结果。例子,

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"

思路是首先遍历shift,判断出最后S到底是往左shift还是往右shift,用一个变量count记录。同时需要注意的是如果这个count的长度大于S的长度,需要取模。最后用substring函数看到底是S的两个substring到底应该如何拼接。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public String stringShift(String s, int[][] shift) {
 3         int count = 0;
 4         for (int[] value : shift) {
 5             if (value[0] == 0) {
 6                 count += value[1];
 7             } else {
 8                 count -= value[1];
 9             }
10         }
11         count = count % s.length();
12         if (count > 0) {
13             s = leftShift(s, count);
14         } else if (count < 0) {
15             s = rightShift(s, -count);
16         }
17         return s;
18     }
19     
20     public static String leftShift(String s, int num) {
21         return s.substring(num) + s.substring(0, num);
22     }
23     
24     public static String rightShift(String s, int num) {
25         return s.substring(s.length() - num) + s.substring(0, s.length() - num);
26     }
27 }

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12710128.html